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
我該怎么做?
uj5u.com熱心網友回復:
如果您也將單個元素更改為串列,則可以在一行中完成。
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'
]
第一行負責將單個元素轉換為串列。
uj5u.com熱心網友回復:
這將做到:
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
uj5u.com熱心網友回復:
您可以遍歷串列并檢查每個元素的型別。如果元素是一個字串,你只需要追加它,但如果它是一個子串列,你需要為子串列中的每個字串生成一個組合。
以下代碼完成了這項作業:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/399294.html
上一篇:將多維陣列轉換為字串的最佳方法
