如何在python中只存储第一个元素

2024-09-28 22:21:24 发布

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

我正在处理一个大的txt文件(1000000个元素),例如:

tammy_wynette    band
tammy_wynette    artist
tammy_wynette    musical_artist
tammy_wynette    group
tammy_wynette    person
tammy_wynette    agent
tammy_wynette    organisation
mansion_historic_district    architectural_structure
mansion_historic_district    place
mansion_historic_district    building
joe_sutter    person
joe_sutter    agent

我只想得到每个项目的第一个元素:

tammy_wynette    band
mansion_historic_district    architectural_structure
joe_sutter    person

我用字典,但我的代码很慢:

dicCSK = {} 
for line in fin:
    line=line.strip('\n')
    try:
        c1, c2 = line.split("\t")
    except ValueError: print line
    if c1 not in dicCSK.keys():
        dicCSK[c1]=c2
        fout.writelines(c1+"\t"+c2+'\n')

有什么快速的方法吗


Tags: 元素bandartistlinepersonc2joec1
1条回答
网友
1楼 · 发布于 2024-09-28 22:21:24

只要做if c1 not in dicCSK:而不是if c1 not in dicCSK.keys():。如果您使用的是python2.x ^{}将以列表的形式返回键,这意味着需要按顺序检查它们

如果以后不使用这些值,不妨改用^{}

dicCSK = set()
for line in fin:
    line=line.strip('\n')
    try:
        c1, c2 = line.split("\t")
    except ValueError: print line
    if c1 not in dicCSK:
        dicCSK.add(c1)
        fout.writelines(c1+"\t"+c2+'\n')

相关问题 更多 >