我有一个文件中的足球统计数据。我可以用两个或多个空格分隔玩家的名字和每个统计数据。我试图让码领导者,所以我需要按第 4 列或第 3 个索引进行排序。
这是我的代码:
import re, sys
try:
file = open("TTL.txt", "r")
except IOError:
print "Could Not Open TTL"
sys.exit()
lines = file.readlines()
for line in lines:
line = re.split("\s\s+", line)
def key_fct(lines):
return (float(lines[3]))
srtlines = sorted(lines, key = key_fct, reverse = True)
for line in srtlines:
print line
file.close()
样本输入:
abel161 8 77 443.0 5 0 11.7 147.2
Abyss ll 38 145 1158.0 11 6 12.8 55.9
AFFISHAUL 34 33 366.0 2 4 17.8 22.7
Assassin NinjaX 25 35 184.0 0 7 10.3 15.1
aubby57 23 165 839.0 11 0 10.5 75.3
B1U3 S4V10R 26 116 380.0 4 6 6.0 29.2
Bigkle 24 47 149.0 2 4 6.7 32.8
BLKSUP3RSA1YAN 5 52 65.0 3 1 9.9 22.7
Booksack 33 85 477.0 5 5 11.0 29.2
Brandon6154xx 23 106 809.0 8 0 17.6 97.0
budweizerbeast 35 472 1640.0 27 9 6.8 94.5
BulkKiller1 31 455 3012.0 40 5 12.6 182.6
Carnage311 30 369 2349.0 25 6 12.8 158.3
cinemagiic 32 12 -8.0 0 2 -1.3 -0.6
Cmfc bumble bee 20 41 253.0 1 0 12.3 28.9
CMFCplaya 19 78 366.0 4 4 9.5 48.9
我收到两个错误:
$./sort.py
Traceback (most recent call last):
File "./sort.py", line 39, in <module>
srtlines = sorted(lines, key = key_fct, reverse=True)
File "./sort.py", line 37, in key_fct
return (float(lines[3]))
ValueError: invalid literal for float(): l
我的文件不是列表列表,但如果我拆分每一行并尝试按第三个索引排序,我仍然会得到文件中名字的第四个字符。