【问题标题】:Zip every element of list A with every element of list B - best "pythonie" way of doing this [duplicate]将列表 A 的每个元素与列表 B 的每个元素压缩 - 最好的“pythonie”方法[重复]
【发布时间】:2015-06-30 17:44:33
【问题描述】:

我有两个要压缩的列表

列表 A:

["hello ", "world "]

列表 B:

["one", "two", "three"]

我想像这样压缩列表中的元素:

[("hello","one")
("hello","two")
("hello","three")
("world","one")
("world","two")
("world","three")]

显然,我可以使用双 for 循环并附加元素,但我想知道这样做的好 pythonie 方式是什么?

【问题讨论】:

  • 您所描述的概念是“Cartesian product”,可以使用itertools.product 来实现,如上面的链接所示。
  • 这就是我要找的词...谢谢!

标签: python python-2.7


【解决方案1】:

这似乎是itertools.product 的完美用例

>>> import itertools
>>> list(itertools.product(['hello', 'world'], ['one', 'two', 'three']))
[('hello', 'one'), ('hello', 'two'), ('hello', 'three'), ('world', 'one'), ('world', 'two'), ('world', 'three')]

【讨论】:

  • 是的。这就是我一直在寻找的。正如@CoryKramer 提到的那样,笛卡尔积。
猜你喜欢
  • 2023-03-19
  • 2022-01-21
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多