【问题标题】:Permutation of two lists [duplicate]两个列表的排列[重复]
【发布时间】:2017-10-01 23:03:33
【问题描述】:

我有两个列表:

first = ["one", "two", "three"]
second = ["five", "six", "seven"]

我希望这两个列表的每一个组合,但第一个列表中的元素始终位于前面。我尝试过这样的事情:

for i in range(0, len(combined) + 1):
    for subset in itertools.permutations(combined, i):
        print('/'.join(subset))

“组合”是这两个列表的组合,但这给了我所有的可能性,我只想要第一个列表中的元素放在首位的那些。例如:

["onefive","twosix","twofive"]

等等。 有谁知道我该怎么做这个?

【问题讨论】:

  • 在这个例子中,你想要所有 9 种组合吗?
  • 是的,我确实想要所有 9 种组合。

标签: python python-2.7 python-3.x list


【解决方案1】:

这应该可以满足您的需求:

>>> ["/".join(x) for x in itertools.product(first, second)]
['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 'two/seven', 'three/five', 'three/six', 'three/seven']
>>> 

你也可以不用itertools:

>>> [x + "/" + y for x in first for y in second]
['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 'two/seven', 'three/five', 'three/six', 'three/seven']
>>> 

【讨论】:

  • OP 想要笛卡尔积。使用itertools.product 是正确的做法。
【解决方案2】:

有时使用普通循环是最简单的:

["{}/{}".format(j,k) for j in first for k in second]

>>> ['one/five', 'one/six', 'one/seven', 'two/five', 'two/six', 
     'two/seven', 'three/five', 'three/six', 'three/seven']

【讨论】:

  • 我同意,它们当然更好。赞成。
猜你喜欢
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 2019-08-05
  • 2019-09-18
  • 1970-01-01
相关资源
最近更新 更多