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

2 投票
3 回答
4959 浏览
提问于 2025-04-18 14:00

我正在处理一个文件,里面有很多列表,列表中又嵌套着其他列表。我想把这些数据整理成参与者人数最多的前五个州和最少的后五个州。

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

这样打印出来的结果大概是这样的:

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

这个结果看起来差不多符合我的需求,但参与者的总人数并不是从多到少排序的,而是根据第一个元素来排序的。我该怎么改才能让它看起来更像这样:

New Jersey 1582,74,15
Illinois 1559,69,13
Florida 1521,44,20
Georgia 1261,51,18
Etc...

这是我第一次在这里提问,任何帮助都非常感谢!:) 另外,我尽量不使用.sort()、find()函数或者"in"操作符,比如“如果6在[5, 4, 7, 6]中...”

编辑*: 通过改变L

L = sorted(allRows,key=lambda x: int(x[1]),reverse=True)

我已经把列表调整成从大到小的顺序了:

State  Total #,% passed,%female
California 4964,76,22
Texas 3979,62,23
New York 1858,69,20
Virginia 1655,60,19
Maryland 1629,66,20
New Jersey 1582,74,15
Illinois 1559,69,13
Florida 1521,44,20

现在我就是搞不清楚怎么才能只取出参与者人数最多的前五个和最少的后五个...

3 个回答

1

看起来你已经把排序搞定了。如果你想要获取前5个和后5个元素,可以使用列表切片的功能:

>>> L = range(15)
>>> L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

>>> L[:5]
[0, 1, 2, 3, 4]

>>> L[-5:]
[10, 11, 12, 13, 14]
1

基本上,你的思路是对的。

接下来你可以对得到的列表进行切片操作:

>>> xs = sorted(range(10), reverse=True)  # A sorted list in descending order
>>> xs
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
>>> xs[:5]  # Top 5
[9, 8, 7, 6, 5]
>>> xs[-5:] # Bottom 5
[4, 3, 2, 1, 0]
>>> 

你应该可以在你的问题中使用类似的切片方法。

可以参考这个有用的指南 Python入门介绍切片部分已标出

7

获取前五个-

top_five = L[:5]

获取后五个-

bottom_five = L[-5:]

详细信息请查看 https://www.programiz.com/python-programming/methods/built-in/slice

撰写回答