排序导入的列表不起作用

2024-09-25 02:25:25 发布

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

我试图排序一个导入的列表,然后显示它,但我已经尝试了各种各样的事情,它没有工作。你知道吗

下面是列表的一个示例:

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

Tags: le列表returnifmaindefsysnom
3条回答

这里需要使用readlines方法,将行读入列表,而不是将所有内容返回到字符串中的read方法。你知道吗

lecture = ouvrir.readlines()

最终课程:

import sys

def liste(entree):
    try:
        ouvrir = open("data2.txt")
    except IOError:
        message1 = "Le fichier data2 n'existe pas."
        return message1
    lecture = ouvrir.readlines()
    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)
            print(message4)
            message4 = sorted(message4)
            print(message4)
            break
        else:
            print("Il faut préciser le nom du fichier à traiter")
            exit()

if __name__ == "__main__":
    main()

运行以下命令:

$ python3 french-program.py data2.txt                                                                         
['Orange\n', 'Apple\n', 'Banada']
['Apple\n', 'Banada', 'Orange\n']

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

with open("data2.txt") as ouvrir:
    lines = ouvrir.readlines()
print sorted(lines)

假设每行包含一个单词,就完成了。你知道吗

假设你想把每一行看作单词(每行一个或多个单词),对每一行的单词进行排序,然后对每一行进行排序

#open file "data2.txt" and readlines into list
#split each line into words and sort that list of sorted lines
#words = list ( list ( word ) )
with open("data2.txt") as ouvrir:
    lines = ouvrir.readlines()
    line_words = [ x for x in [ line.split(":") for line in lines ] ]
    #line_names = [ x[0] for x in [ line.split(":") for line in lines ] ]
print sorted(line_words)

假设每行有一个或多个单词,您想要一个单词的排序列表?下面将嵌套的单词列表展平为单个单词列表

#open file "data2.txt" and readlines into list
#split each line into words, flatten into single list of words
#words = list ( word )
with open("data2.txt") as ouvrir:
    lecture = ouvrir.readlines()
    words = [ word for line in lecture for word in line.split() ]
print sorted(words)

假设你的台词键:值对,例如“苹果:23”?,那么你想要一些不同的东西

你的程序结合了主菜(切片)系统argv[1:])打开并读取文件。你应该把这两个功能分开。这是一种修改代码的方法

import sys

def liste(texte,entree):
    if len(entree) < 1:
        return "Il faut préciser le nom du fichier à traiter"
    elif len(entree) > 1:
        return "Un seul argument est attendu, soit le nom du fichier à traiter."
    with open(texte) as ouvrir:
        lecture = ouvrir.readlines()
        words = [ x.split(":")[0].strip() for x in [ line.strip() for line in lecture ] ]
        words = [ x for x in words if len(x) > 1 ] #filter, remove short words (blanks)
        return lecture
    return "Le fichier {} n'existe pas.".format(texte)

def main():
    while True:
        entree = sys.argv[1:]
        choix = str(entree)
        texte = "data2.txt"
        if texte in choix:
            message4 = sorted(liste(texte,entree))
            print(message4)
            for el in message4: print(el)
            break
        else:
            print("Il faut préciser le nom du fichier à traiter")
            break

if __name__ == "__main__":
    main()
    exit()

你的陈述

ouvrir = open("data2.txt")
lecture = ouvrir.read()

工作原理如下:open("data2.txt")返回一个 标签名为ouvrir,方法.read()返回一个字符串 与"data2.txt"的内容一致,并将其标记为 字符串为lecture。你知道吗

引用lecture时引用的是字符串而不是列表。。。你知道吗

解决问题的聪明方法是使用字符串方法: splitlines();它接受一个字符串并返回一个元素 通过将原始字符串拆分成新行获得的字符串。你知道吗

lecture = ouvrir.read()        # lecture is a string
lecture = lecture.splitlines() # lecture is now a list of strings (lines)

而这正是你需要坚持下去的。请注意 原始内容按换行分开,不换行(即“\n” 字符)在您要排序的行中出现。。。你知道吗

为了完成我的回答,我必须提到方法可以被链接起来

lecture = ouvrir.read().splitlines()

附录

另一种可能性是不使用liste()函数(注意 liste是一个误导性的名称,因为函数返回的是字符串,而不是字符串 list…)并对liste返回的字符串进行后期处理-或者 更确切地说,其他的可能性,即使“应该有一个和” 最好只有一个明显的方法去做“。。。你知道吗

(...)
       if texte in choix:
            message4 = liste(entree)          ## m4 is a string of characters
            message4 = message4.splitlines()  ## m4 is a list of strings,
                                              ##    one string <-> one line in file
            message4 = sorted(message4)       ## m4 contents are sorted now

            for line in message4:             ## let's do something for each line in m4
                if line:                      ## that is, if the line contains something
                    print(line)
            print('############################# alternative')
            lines = sorted(l for l in liste(entree).splitlines() if l)
            for line in lines: print(line)
            print('############################# alternative')
            for line in sorted(l for l in liste(entree).splitlines() if l): print(line)
            print('############################# alternative')
            print('\n'.join(sorted(l for l in liste(entree).splitlines() if l)))
            break
        else:
(...)

相关问题 更多 >