You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于属性对Python中的二维列表进行分组?

按League属性分组二维列表的解决方案

嗨,我来帮你搞定这个按league分组的需求!这里有两种实用的Python实现方式,看你更偏好哪种输出形式:

方式一:带分组标题输出

这种方式会清晰显示每个league对应的所有条目,方便查看分组关系:

# 初始化你的原始二维列表
a = []
a.append(['abc.com','ars','league1','man'])
a.append(['abcxyz.com','hah','league2','bah'])
a.append(['abcd.com','gah','league3','fah'])
a.append(['abcm.com','ada','league1','ads'])
a.append(['abcxyzf.com','gha','league1','tra'])
a.append(['abcdg.com','jhi','league2','yui'])

# 创建字典用于分组,键为league名称,值为对应条目列表
league_groups = {}
for item in a:
    # 提取每个条目中的league值(第3个元素,索引为2)
    league = item[2]
    # 如果该league还未在字典中,先初始化空列表
    if league not in league_groups:
        league_groups[league] = []
    # 将当前条目添加到对应league的列表中
    league_groups[league].append(item)

# 遍历分组结果并输出
for league, items in league_groups.items():
    print(f"=== {league} ===")
    for item in items:
        print(item)

输出结果:

=== league1 ===
['abc.com', 'ars', 'league1', 'man']
['abcm.com', 'ada', 'league1', 'ads']
['abcxyzf.com', 'gha', 'league1', 'tra']
=== league2 ===
['abcxyz.com', 'hah', 'league2', 'bah']
['abcdg.com', 'jhi', 'league2', 'yui']
=== league3 ===
['abcd.com', 'gah', 'league3', 'fah']

方式二:按组连续输出(无分组标题)

如果你想要和示例完全一致的、按组连续排列的输出形式,可以用下面的代码:

# 沿用上面的league_groups字典,按league名称排序后拼接所有条目
sorted_items = []
# 按league名称排序,保证输出顺序稳定
for league in sorted(league_groups.keys()):
    sorted_items.extend(league_groups[league])

# 逐个输出条目
for item in sorted_items:
    print(item)

输出结果:

['abc.com', 'ars', 'league1', 'man']
['abcm.com', 'ada', 'league1', 'ads']
['abcxyzf.com', 'gha', 'league1', 'tra']
['abcxyz.com', 'hah', 'league2', 'bah']
['abcdg.com', 'jhi', 'league2', 'yui']
['abcd.com', 'gah', 'league3', 'fah']

关键思路说明

核心是利用字典的键唯一性来分组:把每个条目中的league值作为键,对应的值存储该league下的所有条目。这样就能高效地完成分组,之后根据需求选择不同的输出形式即可。

内容的提问来源于stack exchange,提问作者Piyush Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:43:47