This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,
visit the help center。
已关闭8年。
我有一个类似于以下文件:
1 a
1 a
1 b
3 s
3 p
3 s
3 y
5 b
...
我正在将其放入键为0列且值为1列的字典中。我正在使用循环,因此当我再次看到键
时,如果新值不在现有键中,则追加新值,因此我的字典看起来像:
test_dict = {'1':[1,b],'3':[s,p,y] ...}
我的代码如下:
test_dict = {}
with open('file.txt') as f:
for line in f:
column = line.split()
if column[0] not in test_dict:
test_dict[column[0]] = column[3]
elif column[3] not in test_dict[column[0]]:
test_dict[column[0]].append(column[3])
else:
break
我在附加行上得到了
str has no attribute append error
。我知道这些列被视为一个字符串,如何在我的代码中对此进行更正?
您不能追加到字符串。您要么要做+=
,要么制作test_dict
列表的元素。您也可以将dict值设为set
,并摆脱所有重复检查的麻烦,尽管您的列表将不再按照首次出现的顺序进行排序。
from collections import defaultdict
test_dict = defaultdict(set)
with open('file.txt') as f:
for line in f:
columns = line.split()
test_dict[columns[0]].add(columns[3])