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

不使用NumPy将元组列表转换为数组的Python实现方案

原生Python实现元组列表转一维展开数组

原始输入数据

tuple_list = [(100, 'Steven', 'King'), (101, 'Brown', 'White'), (102, 'Will', 'Martin')]

核心实现方案

方案1:列表推导式(简洁写法)

通过嵌套推导式直接展开每个元组的元素,生成一维列表:

result = [item for tpl in tuple_list for item in tpl]
# 输出结果:[100, 'Steven', 'King', 101, 'Brown', 'White', 102, 'Will', 'Martin']

方案2:循环+extend方法(直观写法)

遍历元组列表,逐个将元组元素扩展到结果列表中:

result = []
for tpl in tuple_list:
    result.extend(tpl)
# 输出结果与方案1完全一致

匹配示例格式的打印处理

如果需要输出和示例一致的带换行缩进的格式,可添加如下打印逻辑:

print("    [", end="")
for idx, tpl in enumerate(tuple_list):
    if idx != 0:
        print("\n    ", end="")
    # 保留数值和字符串的原始格式
    print(", ".join(str(item) if isinstance(item, int) else repr(item) for item in tpl), end="")
print("]")

执行后输出:

[100, 'Steven', 'King'
    101, 'Brown', 'White'
    102, 'Will', 'Martin']

内容的提问来源于stack exchange,提问作者Jim Macaulay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:01:01