从元组排序 - 索引超出范围

时间:2013-10-12 19:25:25

标签: python sorting indexing

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=malef=female)。

1 个答案:

答案 0 :(得分: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'之前对进行排序,因为字符串是以lexagraphically方式排序的。改为使用数字:

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