Python在lis中的过滤和排序

2024-04-19 13:04:54 发布

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

我只是好像没法让这个工作起来。我需要打开文件游侠.txt. 读每一行,然后把每一行分成一系列单词。检查每个单词是否已经在列表中。如果单词不在列表中,则将其添加到列表中。在程序结束时,按字母顺序对得到的单词进行排序和打印。在

结果应该是: [“a”,“and”“buckle”,“C130”,“countrollin”,“door”,“down”,“four”,“Gonna”,“Jump”,“little”,“out”,“ranger”,“Recon”,“right”,“Shuffle”,“Standstrip”,“the”,“to”,“take”,“trip”,“up”]

我可以把单子列表打印出来,甚至可以从每个单子上取一个词,就这样。在

rangerHandle = open("ranger.txt")
count = 0
rangerList = list()

for line in rangerHandle:
    line = line.rstrip()
    #print line works at this point
    words = line.split() # split breaks string makes another list
    #print words works at this point
    if words[count] not in words: 
        rangerList.append(words[count])        
        count += 1
    print rangerList

在游侠.txt文件是:

^{pr2}$

如果你要投反对票,请至少给出解释。在


Tags: 文件intxt列表countline单词list
2条回答

我们可以创建没有重复的列表。我们稍后将通过将列表转换为集合来删除它们。然后通过执行不区分大小写的排序对集合进行排序:

with open("ranger.txt") as f:
    l = [w for line in f for w in line.strip().split()]
print(sorted(set(l), key=lambda s: s.lower()))

结果:

^{pr2}$

首先,在处理文件(https://docs.python.org/2/tutorial/inputoutput.html)时,最好使用with ...语法。在

第二,如果我是你,我会用集合(https://docs.python.org/2/library/sets.html)代替列表。它们的优点是不能将同一个元素添加两次,因此不需要检查该单词是否已在集合中。对于每一行,我将用该行的单词创建一个新的集合,并使用union方法将其与其他单词合并。在

words = set([])
with open("ranger.txt") as f:
     for line in f:
         newset = set(line.rstrip().split())
         words = words.union(newset)
words = sorted(words) ## this line transforms the set into a sorted list

相关问题 更多 >