【问题标题】:How can I combine a tuple elements into a list in python如何将元组元素组合到python中的列表中
【发布时间】:2017-07-05 09:13:01
【问题描述】:

考虑下面的代码:

list1 = ['1x', '2x']
list2 = ['x18', 'x74']
list3 = [('100p1', '100p2'), ('300p1', '300p2')]

gen_list = [[a,b] for a in list1 for b in list2]

for new_list in gen_list:
    for c in list3:
        print(new_list.extend(c))

我的目标结果是这样的:

[['1x','x18, '100p1', '100p2'],
 ['1x','x74, '100p1', '100p2'],
 ['1x','x18, '300p1', '300p2'],
 ['1x','x74, '300p1', '300p2'],
 ['2x','x18, '100p1', '100p2'],   
 ['2x','x74, '100p1', '100p2'],
 ['2x','x18, '300p1', '300p2'],
 ['2x','x74, '300p1', '300p2']]

但是上面代码的结果是这样的:

None
None
None
None
None
None
None
None

我需要对我的代码进行哪些必要的更正?提前致谢。

【问题讨论】:

  • print(new_list.extend(c)) 打印出None,因为extends 返回None。只需在循环之后打印new_list

标签: python list python-3.x tuples


【解决方案1】:

使用 itertools.product、解包和列表理解

[[l[0], l[2], *l[1]] for l in itertools.product(list1, list3, list2)]

[[l1, l2, *l3] for l1, l3, l2 in itertools.product(list1, list3, list2)]

在 Python 3.5 之前

对于 Python 3.5 之前的版本,您可以这样做

[[l1, l2] + list(l3) for l1, l3, l2 in itertools.product(list1, list3, list2)]

如果您知道 l3 仅包含 2 个元素,您可以使用嵌套解包,如 @ShadowRanger 所述

[[a, b, c1, c2] for a, (c1, c2), b in itertools.product(list1, list3, list2)]

【讨论】:

  • 我在这里尝试了这一行,但仍然返回如下语法错误:Syntax Error: can use starred expression only as assignment target我的系统在 python 3.4 中。我真的不知道为什么这是一个语法错误。
  • 这是 3.5 中的一个新功能 docs.python.org/3/whatsnew/… 当我在我的电脑上时,我会看到 3.4 中的一种工作方式
  • @MaartenFabré:注意:要获得 OP 所需的确切顺序,您需要将 itertools.product 的参数顺序从 list1, list2, list3 更改为 list1, list3, list2,以便从 @ 派生的值987654332@ 交替最快;同样,您可以将 l1, l2, l3 更改为 l1, l3, l2 以便解压缩匹配项。 Demo (w/plain loop to match OP's code)
  • @MaartenFabré:另外,鉴于list3 是固定长度tuples 的list,即使在3.5 之前,您也可以通过使用嵌套解包语法来避免创建/连接临时lists ;它更快,因为它避免了list 构造函数所需的通用函数调用查找和调度:[[a, b, c1, c2] for a, (c1, c2), b in itertools.product(list1, list3, list2)] (Try it online!)
  • 感谢您的努力。我实际上使用了@ShadowRanger 建议的那个,因为它简单明了,不用担心使用 * 或 + 运算符,因为我没有受过良好的训练来使用这些技术。虽然解释很好而且内容丰富。我不妨将它包含在我的个人知识库中。谢谢大家!
猜你喜欢
  • 2016-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-02
  • 2021-11-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-15
相关资源
最近更新 更多