[英]This is a question about lists in python. Can we concatenate two lists
[英]python. combine two lists in the same lenth
問題是使用兩個相同長度的列表來構建擴展列表。 例如,有
qq=['a','b','c']
ww=['d','e','f']
my_function(qq,ww)
#I want to see output like:
output = [['a','b','c'],['a','b','f'],['a','e','c'],['a','e','f'],['d','e','f'],['d','e','c'],['d','b','f'],['d','b','c']]
制作具有以下約束的相同長度列表的所有組合:
重要的是列表中的元素position。
所以 function 需要兩個相同長度的字符串列表。 並返回組合列表。 我該怎么寫這個?
您希望從您的 2 個列表中計算對[a,d] * [b,e] * [c,f]
的乘積。 使用zip
進行配對,將它們組合在一起的product
使整體
from itertools import product
def custom_product(valuesA, valuesB):
return list(product(*zip(valuesA, valuesB))) # return list of tuple
def custom_product(valuesA, valuesB):
return list(map(list, product(*zip(valuesA, valuesB)))) # return list of list
CODE DEMO
這是一個遞歸解決方案。
基本情況當然是每個列表只有一個項目,我們盡可能采用每個列表 output。 對於較長的列表,您會找到不計算第一項的列表的所有可能排列,然后將這些項與每個第一項一起返回。
def solve(list1, list2):
if len(list1) != len(list2):
throw ValueError("Lists should be same length")
if len(list1) == 0:
return []
if len(list1) == 1:
return [[list1[0], list2[0]]
children = solve(list1[1:], list2[1:])
return [[list1[0]] + child for child in children] + [[list2[0]] + child for child in children]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.