繁体   English   中英

如何从包含列表的列表中返回所有子列表

[英]How to return all sub-list from list that contains lists

python l1 =['the movie is',['good','bad'],'and it was',['nice','not bad']]中有一个列表,所以我想要 output:

Output:
the movie is good and it was nice
the movie is good and it was not bad
the movie is bad and it was nice
the movie is bad and it was not bad

我该怎么做?

如果您也将单个元素更改为列表,则可以在一行中完成。

from itertools import product

l1 = ['the movie is', ['good','bad'], 'and it was', ['nice','not bad']]
l1 = [item if isinstance(item, list) else [item] for item in l1]
all_combinations = [' '.join(item) for item in product(*l1)]
print(all_combinations)

Output:
[
    'the movie is good and it was nice',
    'the movie is good and it was not bad',
    'the movie is bad and it was nice',
    'the movie is bad and it was not bad'
]

第一行负责将单个元素转换为列表。

这将做到:

x = 0
while x < 2:
  for a in l1[3]:
    print(f"{l1[0]} {l1[1][x]} {l1[2]} {a}")
  x = x + 1



Output:
the movie is good and it was nice
the movie is good and it was not bad
the movie is bad and it was nice
the movie is bad and it was not bad

您可以遍历列表并检查每个元素的类型。 如果元素是字符串,只需要 append 就可以了,但如果是子列表,则需要为子列表中的每个字符串生成一个组合。

以下代码完成了这项工作:

def get_all_combinations(input_list):

    # Start with a single empty list
    combinations = [[]]

    for e in input_list:
        # If next element in main list is a string, append that string to
        # all combinations found so far
        if isinstance(e, str):
            combinations = [c + [e] for c in combinations]
        # If next element in main list is a sublist, add each strings in
        # sublist to each combination found so far
        elif isinstance(e, list):
            combinations = [c + [e2] for c in combinations for e2 in e]

    # Join all lists of strings together with spaces
    combinations = [' '.join(c) for c in combinations]

    return combinations
    

l1 =['the movie is',['good','bad'],'and it was',['nice','not bad']]

l1_combinations = get_all_combinations(l1)
for combination in l1_combinations:
    print(combination)

Output:

the movie is good and it was nice
the movie is good and it was not bad
the movie is bad and it was nice
the movie is bad and it was not bad

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM