gpt4 book ai didi

Python通过列表过滤和排序

转载 作者:太空宇宙 更新时间:2023-11-04 08:56:58 25 4
gpt4 key购买 nike

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

关于Python通过列表过滤和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29290431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com