简体   繁体   中英

put one element of a list between all elements of another list

I have two list of different lenghts.

list_a = ['pineapple', 'banana', 'mango']
list_b = ['tropical']

I want to combine them as follows:

final_list = ['pineapple', 'tropical', 'banana', 'tropical', 'mango', 'tropical']

the goal is to get a dataframe in the end that includes the variable "fruits" and the variable "origin". I will do that by creating a list that displays only every second element and combine then afterwards.

What I already tried:

fruit_origin = list_b[0]
desired_list = list(map(fruit_origin.__add__, list_a))

but this returns it like this:

['pineappletropical', 'bananatropical', 'mangotropical']

thanks in advance!

You can use zip , itertools.cycle , and a nested comprehension à la:

from itertools import cycle

list_a = ['pineapple', 'banana', 'mango']
list_b = ['tropical']

[x for tpl in zip(list_a, cycle(list_b)) for x in tpl]
# ['pineapple', 'tropical', 'banana', 'tropical', 'mango', 'tropical']

You can also use itertools.chain to flatten the pairs, as suggested by @Matthias:

from itertools import cycle, chain

[*chain(*zip(list_a, cycle(list_b)))]  # Python >= 3.5
# or more verbose
list(chain.from_iterable(zip(list_a, cycle(list_b))))

I'm not sure if I understood your question correctly, but if you want to map the origin which I'm assuming is only the 1 element in the list. You can try this:

desired_list = []
for fruit in list_a:
   desired_list.append(fruit)
   desired_list.append(list_b[0])


print(desired_list)

Output:

['pineapple', 'tropical', 'banana', 'tropical', 'mango', 'tropical']

Combine itertools.cycle , zip and itertools.chain

cycle(['tropical']) 
=> 'tropical', 'tropical', 'tropical', 'tropical', ...

zip(['pineapple', 'banana', 'mango'], ['tropical', 'tropical', 'tropical'])
=> [('pineapple', 'tropical'), ('banana', 'tropical'), ('mango', 'tropical')]

list(chain(*[('pineapple', 'tropical'), ('banana', 'tropical'), ('mango', 'tropical')]))
=> ['pineapple', 'tropical', 'banana', 'tropical', 'mango', 'tropical']

Final code

result = list(chain(*zip(list_a, cycle(list_b))))

You can multiply second list by number of items in the first list, and use zip and comprehension like this:

[item for x in zip(list_a, list_b*len(list_a)) for item in x]
Out[7]: ['pineapple', 'tropical', 'banana', 'tropical', 'mango', 'tropical']

I think a nested loop is more readable in this case than a one liner

list_a = ['pineapple', 'banana', 'mango']
list_b = ['tropical']

final_list = []
for a in list_a:
    final_list.append(a)
    for b in list_b:
        final_list.append(b)

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