简体   繁体   中英

python. combine two lists in the same lenth

The problem is to build extended lists out of using two same length lists. for example, there is

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']]

all the combinations of making the same length list with a constraint of:

  • if a is chosen then d cannot be chosen, same logic,
  • if b is chosen then e cannot be chosen,
  • if c is chosen then f cannot be chosen.

The important thing is the elements' position in the list.

so the function takes two same length list of strings. and returns the list of the combinations. How should I write this?

You want, from your 2 lists, to do the product of the pairs [a,d] * [b,e] * [c,f] . Using zip to pair, and product to combine them all makes the whole to

  • take just one element of each pair, so one element per indice, with zip
  • build all the combinations betwween the pairs, with 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

Here's a recursive solution.

The base case is of course when each list has just one item and we take each list as possible output. For longer lists, you find all the possible arrangements of the lists not counting the first items, and then return those items with each of the first items.


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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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