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"]
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']
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With