-1
def mkEntry(file1):
    for line in file1:
        lst = (line.rstrip().split(","))
        print("Old", lst)
        print(type(lst))
        lst = tuple(lst)
        print(type(lst)) #still showing type='list'
        print("Old2", lst)
    sorted(lst, key=operator.itemgetter(1,2))


def main():
    openFile = 'yob' + input("Enter the year <Do NOT include 'yob' or .'txt' : ") + '.txt'
    file1 = open(openFile)
    mkEntry(file1)

main()

我收到的错误:

Traceback (most recent call last):
  File "/Users/ranbir/Desktop/names/top101.py", line 20, in <module>
    main()
  File "/Users/ranbir/Desktop/names/top101.py", line 18, in main
    mkEntry(file1)
  File "/Users/ranbir/Desktop/names/top101.py", line 12, in mkEntry
    sorted(lst, key=operator.itemgetter(1,2))
IndexError: string index out of range

文件:

Tom,M,1658
Anthony,M,985
Lisa,F,88976
Ben,M,6989
Shelly,F,8975

我需要帮助排序从最小数字到最大数字F的顺序。M输出应如下所示:

Shelly,F,8975
Lisa,F,8976
Ben,M,698
Anthony,M,985
Tom,M,1658

所以基本上,女性首先是最小到最大的数字,然后是男性,然后是最小到最大的数字(M=male, f=female)。

4

1 回答 1

1

您不断地lst在循环中重新分配:

for line in file1:
    lst = (line.rstrip().split(","))
    lst = tuple(lst)

sorted(lst, key=operator.itemgetter(1,2))

您没有构建所有条目的最终列表。为此,您需要一个单独的列表对象:

results = []
for line in file1:
    lst = line.rstrip().split(",")
    lst = tuple(lst)
    results.append(lst)

return sorted(results, key=operator.itemgetter(1,2))

请注意,您还需要返回排序列表。

这仍然不会达到您的预期,因为您的最后一个元素(在索引 2 处)仍然是一个字符串。'10'在之前 '91234'排序,因为字符串是按字典顺序排序的。改为数字:

results = []
for line in file1:
    lst = line.rstrip().split(",")
    lst[2] = int(lst[2])
    lst = tuple(lst)
    results.append(lst)

return sorted(results, key=operator.itemgetter(1,2))
于 2013-10-12T19:35:00.870 回答