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

Python如何将足球赛果嵌套数组展开为100个元素的一维列表?

解决方案

你当前的双层嵌套列表推导式会先为每个team2的得分生成10个比分的子列表,最终得到10个子列表组成的二维结构。可通过以下两种方式实现需求:

方案1:生成阶段直接输出一维列表

调整列表推导式的循环层级,不需要嵌套括号,直接生成一维结构:

import numpy as np

team1 = np.array(list(range(10)))
team2 = np.array(list(range(10)))

# 直接生成包含100个比分的一维列表
scores = [[x, y] for y in team2 for x in team1]
test_scores = scores
print(len(test_scores)) # 输出为100,符合要求

方案2:已有嵌套列表的摊平处理

如果已经生成了嵌套的test_scores,可以用以下两种方法拆分为一维列表:

  • 纯Python列表推导式实现:
flatten_scores = [score for sub_list in test_scores for score in sub_list]
  • 调用numpy内置方法实现(适合数据量更大的场景):
import numpy as np
flatten_scores = np.array(test_scores).reshape(-1, 2).tolist()

以上两种方法得到的结果都是长度为100的一维列表,每个元素为对应比赛比分的二元列表,可直接传入后续函数遍历使用。

内容的提问来源于stack exchange,提问作者Jesse Holliday

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:36:00