将列表排序为按字母顺序排列

时间:2015-04-25 18:20:44

标签: python

我有一个列表,我想按字母顺序排序,但它不起作用。我写过这篇文章,但效果不好:

#!usr/bin/python
f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
    myList.append(line)
f.close()
print myList
subList = []

for i in range(1, len(myList)):
    print myList[i]
    subList.append(myList[i])

subList.sort()
print subList

这是文本文件:

Test List
ball
apple
cat
digger
elephant  

这是输出:

Enigmatist:PYTHON lbligh$ python test.py
['Test List\n', 'ball\n', 'apple\n', 'cat\n', 'digger\n', 'elephant']
ball

apple

cat

digger

elephant
['apple\n', 'ball\n', 'cat\n', 'digger\n', 'elephant'] 

任何故障排除都非常有用。感谢

N.B。我正在使用python 2.7.9

3 个答案:

答案 0 :(得分:1)

你只是忘了覆盖文件,就是这样。

with open('test.txt', 'r') as inf:
    lst = inf.readlines()  # much easier than iterating and accumulating

lst[1:] = sorted(lst[1:])  # this will leave the first line: "Test List" intact

with open('test.txt', 'w') as outf:
    outf.writelines(lst)  # re-write the file

答案 1 :(得分:0)

试一试:

f = open("test.txt","r") #opens file with name of "test.txt"
myList = []
for line in f:
    myList.append(line)
f.close()
print myList
subList = []
for i in range(1, len(myList)):
    subList.append(myList[i])

subList.sort()
with open("test.txt","w") as f:
    for x in subList:
        f.write(str(x))

答案 2 :(得分:-1)

print(*sorted([i.strip() for i in open('test.txt', 'r')], key=lambda x: x.lower()), file=open('output.txt', 'w'))