我试图排序一个导入的列表,然后显示它,但我已经尝试了各种各样的事情,它没有工作。你知道吗
下面是列表的一个示例:
pommes : 54
bananes : 18
oranges : 30
ananas :12
clémentines :77
cerises de terre: 43
输出应按字母顺序排列
这就是我得到的
['\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '0', '1', '1', '2',
'3', '3', '4', '4', '5', '7', '7', '8', ':', ':', ':', ':', ':', ':', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e'
, 'e', 'e', 'g', 'i', 'i', 'l', 'm', 'm', 'm', 'n', 'n', 'n', 'n', 'n', 'n', 'n', 'o', 'o', 'p', 'r', 'r', 'r', 'r', 's', 's', 's', 's', 's', 's', 's', 't', 't
', 'é']
这是我的密码
import sys
def liste(entree):
try:
ouvrir = open("data2.txt")
except IOError:
message1 = "Le fichier data2 n'existe pas."
return message1
lecture = ouvrir.read()
if len(entree) < 1:
message2 = "Il faut préciser le nom du fichier à traiter"
return message2
elif len(entree) > 1:
message3 = "Un seul argument est attendu, soit le nom du fichier à traiter."
return message3
else:
return lecture
def main():
while True:
entree = sys.argv[1:]
choix = str(entree)
texte = "data2.txt"
if texte in choix:
message4 = liste(entree)
message4 = sorted(message4)
print(message4)
break
else:
print("Il faut préciser le nom du fichier à traiter")
exit()
if __name__ == "__main__":
main()
这里需要使用
readlines
方法,将行读入列表,而不是将所有内容返回到字符串中的read
方法。你知道吗最终课程:
运行以下命令:
试试readlines,(请看这个答案:How do I read a file line-by-line into a list?,也请看:Reading a text file and splitting it into single words in python)。你知道吗
哦,而且“with open()”是惯用的(与其说是try,不如说是try)
假设每行包含一个单词,就完成了。你知道吗
假设你想把每一行看作单词(每行一个或多个单词),对每一行的单词进行排序,然后对每一行进行排序
假设每行有一个或多个单词,您想要一个单词的排序列表?下面将嵌套的单词列表展平为单个单词列表
假设你的台词键:值对,例如“苹果:23”?,那么你想要一些不同的东西
你的程序结合了主菜(切片)系统argv[1:])打开并读取文件。你应该把这两个功能分开。这是一种修改代码的方法
你的陈述
工作原理如下:
open("data2.txt")
返回一个 标签名为ouvrir
,方法.read()
返回一个字符串 与"data2.txt"
的内容一致,并将其标记为 字符串为lecture
。你知道吗引用
lecture
时引用的是字符串而不是列表。。。你知道吗解决问题的聪明方法是使用字符串方法:
splitlines()
;它接受一个字符串并返回一个元素 通过将原始字符串拆分成新行获得的字符串。你知道吗而这正是你需要坚持下去的。请注意 原始内容按换行分开,不换行(即“\n” 字符)在您要排序的行中出现。。。你知道吗
为了完成我的回答,我必须提到方法可以被链接起来
附录
另一种可能性是不使用
liste()
函数(注意liste
是一个误导性的名称,因为函数返回的是字符串,而不是字符串 list…)并对liste
返回的字符串进行后期处理-或者 更确切地说,其他的可能性,即使“应该有一个和” 最好只有一个明显的方法去做“。。。你知道吗相关问题 更多 >
编程相关推荐