我是Python新手,我的第一个Python脚本有一些问题。我有一个数据列表,其.tag
属性最初设置为0。
lst = [a, b, c, d, e, f]
for x in lst:
x.tag = 0
然后,我获得了真实标签和列表中相应元素索引的结果。它存储在词典列表中。显然,列表中的某些元素具有多个标签。现在,我想更新列表中所有元素的标签,以便每个元素都具有诸如的标签属性f.tag = [2,3,4,5]
。我写了以下脚本。这个想法是循环遍历每个字典并获得索引和标签。然后循环遍历每个索引,并检查列表的相应元素是否具有标签=0。如果是,请将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)
但是,运行此命令后,我再也看不到“代码永远在这里”被打印出来。然后,我检查列表,我只看到所有具有非零实数标签的元素都被更新,但是只有一次。这意味着不能再次更新元素的标签。绝对不行,因为有些元素具有多个标签并且需要不断更新。我不知道我的代码中可能出了什么问题。
逻辑相当复杂,但是我认为它确实可以实现您想要的功能。我怀疑问题出在您的输入上results
。尤其:
(2)
,请将其更改为(2,)
以便可以正确迭代。(2)
只是求值2
而不能迭代。{'indices':(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]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句