![](/img/trans.png)
[英]How to replace strings in list from a dictionary with all possible combinations
[英]How to find all possible combinations from nested list containing list and strings?
我試圖從列表中獲取所有可能的模式,如:
input_x = ['1', ['2', '2x'], '3', '4', ['5', '5x']]
我們看到,它有2個嵌套列表['2', '2x']
和['5', '5x']
。
這意味着所有可能的模式都是4(2個案例x 2個案例),期望輸出為:
output1 = ['1','2' , '3', '4', '5']
output2 = ['1','2x', '3', '4', '5']
output3 = ['1','2' , '3', '4', '5x']
output4 = ['1','2x', '3', '4', '5x']
我試圖搜索如何,但我找不到任何例子(因為我不知道搜索“關鍵字”)
我認為python有內部庫/方法來處理它。
實現此目的的一種方法是使用itertools.product
。 但是為了使用它,您需要首先將列表中的單個元素包裝到另一個列表中。
例如,首先我們需要轉換您的列表:
['1', ['2', '2x'], '3', '4', ['5', '5x']]
至:
[['1'], ['2', '2x'], ['3'], ['4'], ['5', '5x']]
這可以通過以下列表理解來完成:
formatted_list = [(l if isinstance(l, list) else [l]) for l in my_list]
# Here `formatted_list` is containing the elements in your desired format, i.e.:
# [['1'], ['2', '2x'], ['3'], ['4'], ['5', '5x']]
現在在上面list
的解壓縮版本上調用itertools.product
:
>>> from itertools import product
# v `*` is used to unpack the `formatted_list` list
>>> list(product(*formatted_list))
[('1', '2', '3', '4', '5'), ('1', '2', '3', '4', '5x'), ('1', '2x', '3', '4', '5'), ('1', '2x', '3', '4', '5x')]
如果您不想將列表轉換為所有子列表,那么您可以嘗試這樣的事情:
input_x = ['1', ['2', '2x'], '3', '4', ['5', '5x'],['6','6x']]
import itertools
non_li=[]
li=[]
for i in input_x:
if isinstance(i,list):
li.append(i)
else:
non_li.append(i)
for i in itertools.product(*li):
sub=non_li[:]
sub.extend(i)
print(sorted(sub))
輸出:
['1', '2', '3', '4', '5', '6']
['1', '2', '3', '4', '5', '6x']
['1', '2', '3', '4', '5x', '6']
['1', '2', '3', '4', '5x', '6x']
['1', '2x', '3', '4', '5', '6']
['1', '2x', '3', '4', '5', '6x']
['1', '2x', '3', '4', '5x', '6']
['1', '2x', '3', '4', '5x', '6x']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.