str没有附加属性

2024-04-23 02:30:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个类似的文件:

1 a  
1 a  
1 b  
3 s  
3 p  
3 s  
3 y  
5 b  
...  

我正在把它编成一个字典,其中key是第0列,value是第1列。我正在使用循环,因此当我再次看到键时,如果新值不在现有键中,我将附加新值,因此我的字典将如下所示:

测试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  

我在append行得到一个str has no attribute append error。我知道列被视为一个字符串,如何在代码中更正这个问题?你知道吗


Tags: 文件key代码intest字典valuewith
3条回答

不能附加到字符串。您要么要执行+=,要么要生成test_dict列表的元素。您还可以将dict值set设置为s,并去掉所有重复检查,尽管您的列表将不再按第一次出现的顺序排序。你知道吗

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])

您还可以使用groupby然后使用set删除重复项来获得类似的结果

>>> from itertools import groupby
>>> from operator import itemgetter
>>> {k: list(set(e for _,e in v))
        for k,v in groupby((e.split() for e in foo),
               key = itemgetter(0))}
{'1': ['a', 'b'], '3': ['y', 'p', 's'], '5': ['b']}

column[3]是字符串,test_dict[column[0]]将是字符串。你想列个单子吗?你知道吗

test_dict[column[0]] = [column[3]]

相关问题 更多 >