Skip to main content
 首页 » 编程设计

Python通过列表过滤和排序

2025年05月04日63hnrainll

我似乎无法让它发挥作用。我需要打开文件 ranger.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 

ranger.txt 文件是:

C130 rollin down the strip 
Recon ranger 
Gonna take a little trip 
Stand up, buckle up, 
Shuffle to the door 
Jump right out and count to four 

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

请您参考如下方法:

我们可以在不查找重复项的情况下创建列表。稍后我们将通过将列表转换为集合来删除它们。然后我们通过不区分大小写的排序对集合进行排序:

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

结果:

[ 
    'a', 'and', 'buckle', 'C130', 'count', 'door', 'down', 'four',  
    'Gonna', 'Jump', 'little', 'out', 'ranger', 'Recon', 'right',  
    'rollin', 'Shuffle', 'Stand', 'strip', 'take', 'the', 'to', 'trip', 
    'up,' 
]