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
)。
'lst'只是*一行*一個元組。不是元組列表。您正在嘗試對'('Shelly','F','8975')進行排序。 –
糟糕,它假定在for循環之外。我更新了。 – user1552400
'Ben,M,6989' in input,'Ben,M,698' in output? – falsetru