Python 属性只能在嵌套for循环中更新一次
我是Python新手,对我的第一个Python脚本有一些问题。我有一个带有Python 属性只能在嵌套for循环中更新一次,python,list,dictionary,for-loop,if-statement,Python,List,Dictionary,For Loop,If Statement,我是Python新手,对我的第一个Python脚本有一些问题。我有一个带有.tag属性的数据列表,该属性最初设置为0 lst = [a, b, c, d, e, f] for x in lst: x.tag = 0 然后,我得到了列表中实际标记和相应元素索引的结果。它存储在词典列表中。显然,列表中的某些元素有多个标记。现在我想更新列表中所有元素的标记,这样每个元素都有类似于f.tag=[2,3,4,5]的标记属性。我写了下面的脚本。其思想是循环遍历每个字典并获得索引和标记。然后循环遍历
.tag
属性的数据列表,该属性最初设置为0
lst = [a, b, c, d, e, f]
for x in lst:
x.tag = 0
然后,我得到了列表中实际标记和相应元素索引的结果。它存储在词典列表中。显然,列表中的某些元素有多个标记。现在我想更新列表中所有元素的标记,这样每个元素都有类似于f.tag=[2,3,4,5]
的标记属性。我写了下面的脚本。其思想是循环遍历每个字典并获得索引和标记。然后循环遍历每个索引,并检查列表的相应元素是否具有标记=0。如果是,将0更改为新标记作为单个元素列表;如果没有,这意味着它以前已经更新过,所以只需附加新标记即可。我的脚本如下:
results = [{'indices':(2), 'tag':0}, {'indices':(1,3), 'tag':1}, {'indices':(0,3,4,5), 'tag':2}, {'indices':(4,5), 'tag':3}, {'indices':(1,5), 'tag':4}, {'indices':(5), 'tag':5}]
for dct in results:
indices = dct['indices']
t = dct['tag']
for i in indices:
if lst[i].tag == 0:
lst[i].tag = [t]
elif t not in lst[i].tag:
print('The code ever goes here')
lst[i].tag.append(t)
然而,在我运行这个程序之后,我从来没有看到“代码曾经出现在这里”被打印出来。然后我检查列表,我只看到所有带有非零实标记的元素被更新,但只有一次。这意味着不能再次更新元素的标记。这绝对不行,因为有些元素有多个标记,需要不断更新。我不知道我的代码中可能出现了什么错误。逻辑相当复杂,但我认为它可以满足您的要求。我怀疑问题在于您的输入
结果
。特别是:
- 对于像
这样的单元素索引,请将其更改为(2)
,以使其正确可编辑<代码>(2)的计算结果仅为(2,)
,无法迭代2
- 最后一个元素应该是
,而不是{'index':(5,),'tag':5}
{'5':,'tag':5}
class A:
def __init__(self):
self.tag = 0
lst = [A() for _ in range(6)]
results = [
{"indices": (2,), "tag": 0},
{"indices": (1, 3), "tag": 1},
{"indices": (0, 3, 4, 5), "tag": 2},
{"indices": (4, 5), "tag": 3},
{"indices": (1, 5), "tag": 4},
{"indices": (5,), "tag": 5},
]
for dct in results:
indices = dct["indices"]
t = dct["tag"]
for i in indices:
if lst[i].tag == 0:
lst[i].tag = [t]
elif t not in lst[i].tag:
print("The code does go here")
lst[i].tag.append(t)
接
for x in lst:
print(x.tag)
>
[2]
[1, 4]
[0]
[1, 2]
[2, 3]
[2, 3, 4, 5]
如果元素具有标记属性,我将使用该属性来保存标记列表…非常干净:
In [38]: class thing():
...: def __init__(self):
...: self.tags = [0,] # the default
...:
...:
...:
In [39]: # make some "things"
In [40]: x = thing()
In [41]: y = thing()
In [42]: z = thing()
In [43]: x.tags
Out[43]: [0]
In [44]: x.tags.append(44)
In [45]: x.tags.append(-2)
In [46]: z.tags.append(3)
In [47]: for t in [x, y, z]:
...: print(t.tags)
...:
[0, 44, -2]
[0]
[0, 3]
您能提供一个输入和预期输出的示例吗?
[0,]
您不需要后面的逗号。有点小…但可以。