【问题标题】:How to return all sub-list from list that contains lists如何从包含列表的列表中返回所有子列表
【发布时间】:2021-12-29 07:30:19
【问题描述】:

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

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

我该怎么做?

【问题讨论】:

  • 似乎是存储此类数据的不好方法,但它应该是可行的。字符串中的项目数是固定的还是固定的?
  • 包含您尝试过的内容,看看我们是否可以改进它
  • 我建议使用不同类型的结构...可能是包含主字符串和变体的字典列表?

标签: python string algorithm substring


【解决方案1】:

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

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]

# finding all combinations
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'
]

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

【讨论】:

    【解决方案2】:

    这样就可以了:

    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
    

    【讨论】:

    • 这对于示例输入来说太具体了。
    【解决方案3】:

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

    下面的代码完成了这项工作:

    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)
    

    输出:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-14
      • 2014-06-17
      • 2018-10-08
      • 2020-03-28
      • 2019-10-04
      • 2022-12-31
      • 2014-01-20
      • 1970-01-01
      相关资源
      最近更新 更多