[英]Is there a way to enumerate a list or dictionary that share the same index?
I want to enumerate a list or dictionary, if the items share the same value or are equal I want them to use 1 index. 我想枚举列表或字典,如果项目共享相同的值或相等,则我希望它们使用1索引。
This is my code: 这是我的代码:
def print_data(league_results):
for i, (team, points) in
enumerate(sorted(league_results.items(), key=lambda x: x[1],
reverse=True), 1):
if points == 1:
i = i
print('{}. {}, {}'.format(i, team.strip(''), points))
Output 输出量
1. Man City, 6
2. Liverpool, 5
3. Everton, 1
4. Stoke, 1
5. Fulham, 0
This is my desired output: If a team share a point they should have the same index. 这是我想要的输出:如果一个团队分享一个分数,他们应该具有相同的索引。 Everton & Stoke must share the same index.
Everton&Stoke必须共享相同的索引。
1. Man City, 6
2. Liverpool, 5
3. Everton, 1
3. Stoke, 1
4. Fulham, 0
You can use itertools.groupby
: 您可以使用
itertools.groupby
:
def print_data(league_results):
grouped_results = itertools.groupby(
sorted(league_results.items(), key=lambda x: x[1], reverse=True),
key=lambda x: x[1]
)
for i, (_, teams) in enumerate(grouped_results, 1):
for team, points in teams:
print('{}. {}, {}'.format(i, team.strip(''), points))
Results: 结果:
1. Man City, 6
2. Liverpool, 5
3. Everton, 1
3. Stoke, 1
4. Fulham, 0
Here you have the live example 这里有现场示例
Explanation: 说明:
groupby
will make an iterable with matching between the amount of points and the teams (it will group them if they are sorted) giving us an iterable of (points, [(team, points), ...]), ...
. groupby
将使点数与团队之间的匹配变得可迭代(如果对它们进行排序将对其进行分组),从而为我们提供(points, [(team, points), ...]), ...
的可迭代性。 Hence when enumerating it you will enumerate this groups, that will be our index i
. 因此,在枚举它时,您将枚举这些组,这将成为我们的索引
i
。 Since we want the enumeration to start from 1
instead of 0
we simply ask the function to start from it enumerate(iterable, start_enumerate_value)
因为我们希望枚举从
1
而不是0
开始,所以我们只是简单地要求函数从它开始enumerate(iterable, start_enumerate_value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.