使用Python中的第二列按字母顺序对文本文件进行排序

时间:2018-11-19 21:57:50

标签: python python-3.x python-2.7 text-files alphabetical-sort

我尝试了各种方法来使文本文件按姓氏的字母顺序排序。当前将姓氏读为每个拆分行的第二列。我可以毫无问题地按第一列进行排序。我尝试放入last.sort()或使用sorted(myList),但是它不起作用。我什至尝试导入itemgetter。请帮忙! Pictures of results ... previous results with column one sorted ... Picture of Text File

TXT文件信息: 654,琼斯,1,18:03 733,史密斯,3,18:09 394,Jackson,4,18:22 876,科尔,1,18:23 555,Cruz,5,18:28 741,Martinez,2,18:33 499,戴维斯,2,18:36 338,钝,3,18:44 632,帕顿,5,18:45 712,乔伊斯,4,18:49 112,Shoemaker,1,18:55 321,Smart,5,18:58 564,Love,2,19:01 843,Grove,4,19:05 933,Ham,3,19:10

with open("Race_Results_Sample.txt", "r")as myList:
    myList= myList.read().split()
    sorted(myList, key=lambda kv: kv[1])
    for line in myList:
        num, last, org, time = line.split(",")
        print num, last, org, time

1 个答案:

答案 0 :(得分:1)

尝试将文本解析为2d列表,例如

with open("test.txt", "r")as myList:
    myList = myList.read()
    myList = [l.split(",") for l in myList.splitlines()]
    myList = sorted(myList, key=lambda kv: kv[1])
    for line in myList:
        num, last, org, time = line
        print num, last, org, time

每个换行符分割一次,然后每个逗号再次换行。