Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two python list using its value logic - Python

Tags:

python

list

I would like to combine two lists in Python to make one list in the following way:

a = [1,1,1,2,2,2,3,3,3,3]

b= ["Sun", "is", "bright", "June","and" ,"July", "Sara", "goes", "to", "school"]

and the output:

c= ["Sun is bright", "June and July", "Sara goes to school"]
like image 627
Afnan Avatar asked May 05 '26 03:05

Afnan


2 Answers

Use a for loop to first accumulate the words into some kind of mapping data structure, and then use a list comprehension to create the desired output.

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for k, v in zip(a, b):
...     d[k].append(v)
...     
>>> [' '.join(d[k]) for k in sorted(d)]
['Sun is bright', 'June and July', 'Sara goes to school']
like image 120
wim Avatar answered May 07 '26 15:05

wim


Assuming that:

a and b have the same length

a is ordered

a begin with 1

Try:

a = [1,1,1,2,2,2,3,3,3,3]

b= ["Sun", "is", "bright", "June","and" ,"July", "Sara", "goes", "to", "school"]

c = []
for i in range(len(a)):
    if len(c)<a[i]:
       c.append(b[i])
    else:
       c[a[i]-1] += " " + b[i]

print c
like image 33
Martín Muñoz del Río Avatar answered May 07 '26 16:05

Martín Muñoz del Río



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!