简体   繁体   中英

Python: how to replace an element in a list with all elements from another list?

I have two lists in Python that look like this:

 lst = [1, '?2']
 replace_lst1 = ['a','b','c']

For each occurrence of '?2' in lst , I would like to replace it with each element from replace_lst1 thereby producing a list of lists as follows:

res = [ [1,'a'], 
        [1,'b'],
        [1,'c'] ]

Similarly, if I have the following lists:

lst = [1, '?2','?3']
replace_lst1 = ['a','b','c']
replace_lst2 = ['A', 'B', 'C']

I would like to replace '?2' with each element from replace_lst1 and '?3' with each element from replace_lst2 , thereby exploring all possible permutations. The result should look like this:

res = [ [1,'a','A'], 
        [1,'a','B'],
        [1,'a','C'],
        [1,'b','A'], 
        [1,'b','B'],
        [1,'b','C'],
        [1,'c','A'], 
        [1,'c','B'],
        [1,'c','C'] ]

It would be great if you could provide me with some suggestions how to proceed.

Thanks!

If you change your data structure slightly, this is a trivial problem for the itertools module :

>>> lst = [1]
>>> combine = [["a", "b", "c"], ["A", "B", "C"]]
>>> import itertools
>>> [lst+list(item) for item in itertools.product(*combine)]
[[1, 'a', 'A'], [1, 'a', 'B'], [1, 'a', 'C'], [1, 'b', 'A'], [1, 'b', 'B'], 
 [1, 'b', 'C'], [1, 'c', 'A'], [1, 'c', 'B'], [1, 'c', 'C']]
>>> from itertools import product
>>> lst = [1]
>>> combine = [["a", "b", "c"], ["A", "B", "C"]]
>>> list(product(*[lst]+combine))
[(1, 'a', 'A'), (1, 'a', 'B'), (1, 'a', 'C'), (1, 'b', 'A'), (1, 'b', 'B'), (1, 'b', 'C'), (1, 'c', 'A'), (1, 'c', 'B'), (1, 'c', 'C')]

you could also use

list(product(lst, replace_lst1, replace_lst2))

I would use itertools.product, plus a test to replace the ? by the value :

lst = [1, '?2','?3']
replace_lst1 = ['a','b','c']
replace_lst2 = ['A', 'B', 'C']
res = []
#put as many replace_lst as you need here
for values in itertools.product(replace_lst1, replace_lst2):
    val_iter = iter(values)
    res.append([x if str(x).find('?') == -1 else next(val_iter) for x in lst])

The use of val_iter allows for the ?* to be placed anywhere (but not in any order, though).

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