小编Mic*_*eid的帖子

如何从嵌套列表中只获取前 5 个和后 5 个列表?

没错,我正在处理一个列表中包含一堆列表的文件。我正在尝试按参与者总数的前 5 个州和后 5 个州来安排它们。

import csv
from operator import itemgetter #not really using this right now
crimefile = open('APExam.txt', 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]
L = sorted(allRows,key=lambda x: x[1])
for item in L:
    print item[0],','.join(map(str,item[1:]))
Run Code Online (Sandbox Code Playgroud)

它打印出这样的东西:

State  Total #,% passed,%female
Wyoming 0,0,0
New Hampshire 101,76,12
Utah 103,54,4
Mass 1067,67,18
Montana 11,55,0
Iowa 118,80,9
Alabama 126,79,17
Georgia 1261,51,18
Florida 1521,44,20
Illinois 1559,69,13
New Jersey 1582,74,15
Maine 161,67,16
Run Code Online (Sandbox Code Playgroud)

这以几乎我正在寻找的方式打印文件,但参与者的总数没有按从大到小的排序;它通过查看第一个元素进行排序。我如何将其更改为看起来更像:

New Jersey 1582,74,15
Illinois 1559,69,13
Florida …
Run Code Online (Sandbox Code Playgroud)

python sorting list nested-lists python-2.7

2
推荐指数
1
解决办法
3945
查看次数

标签 统计

list ×1

nested-lists ×1

python ×1

python-2.7 ×1

sorting ×1