python - Python 列表中的组合

标签 python

我有(比如 2 个)列表,我想获得列表中元素之间的所有组合,但我想放入条件。例如,如果第一个列表中的元素是 "yes" ,如果第二个元素在创建组合时是“确定的”,并且如果元素是“否”则应考虑。

我已经知道如何在列表列表之间获得各种组合(我使用了 itertools 库):

import itertools

list_d = [["yes","no"],["ifyes","ifyes2","ifno"]]

#in this way we can use a for loop to iterate through the combinations
iterator_d=itertools.product(*list_d)

所以我希望但没有得到的输出应该是这样的:

["yes","ifyes"] ,["yes","ifyes2"],["no","ifno"]

最佳答案

这是一个列表理解,可以为您提供两个列表所需的输出。

import itertools

list_d = [["yes","no"],["ifyes","ifyes2","ifno"]]

#in this way we can use a for loop to iterate through the combinations
iterator_d=itertools.product(*list_d)

x = [[i,j] for i,j in iterator_d if i in j]
Result:
x = [['yes', 'ifyes'], ['yes', 'ifyes2'], ['no', 'ifno']]

关于python - Python 列表中的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57974287/

相关文章:

python - 根据 Python 中的数组值拆分数组

Python 文件读取问题,可能的 infile 循环?

python - 模板内的 Django Cookie 值

python - 我如何在 python lxml、XPath 中使用正则表达式

python - 转换 pandas 系列和日期时间对象

python - 我怎样才能找到kafka配置文件?

python - 使用 numpy 创建任意形状的单位矩阵

python - Theano - 按组求和

python - 使用 'awk'/Python 删除重复的功能 block (通用解决方案)

Python:循环内的函数是否是好的做法