【问题标题】:How to create a new list that is combination of 2 different lists elements without repetition?如何创建一个由 2 个不同列表元素组合而不重复的新列表?
【发布时间】:2019-02-01 20:37:40
【问题描述】:

我正在尝试创建一个有 2 个刺激物的画布。请注意,刺激列表可以更长。

sti1 = ["death", "pain"]
sti2 = ["glass", "book"]

这些刺激将显示如下:

第 1 帧:死亡 - 书 / 第 2 帧:玻璃 - 痛苦

但他们必须正确洗牌。我的意思是,如果有“死亡 x 书”的组合,就不能再有另一个了。此外,必须显示所有组合。此外,所有帧必须包含一个来自 sti1 的单词和一个来自 sti2 的单词。

这是我的想法:

  1. 创建一个包含所有组合的组合列表。

  2. 使用 for 循环进行迭代。

如果除了创建组合列表并对其进行迭代之外,还有其他解决方案,我愿意接受新事物。

我试过了: 随机选择 itertools.permutations itertools.combinations(最接近的答案,但这只能组合 1 个列表,如 sti1)

预期结果: combination_list = [(death, glass), (death, book), (pain, glass), (pain, book)]

【问题讨论】:

    标签: python random iteration combinations


    【解决方案1】:

    你想要的itertools.product:

    from itertools import product
    list(product(sti1,sti2))
    [('death', 'glass'), ('death', 'book'), ('pain', 'glass'), ('pain', 'book')]
    

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 2015-09-02
      • 2021-12-10
      • 2023-02-19
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      相关资源
      最近更新 更多