我有(比如 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/