below are 2 lst1 and lst2 and expected output is in output as below.
lst1 = ['q','r','s','t','u','v','w','x','y','z']
lst2 =['1','2','3']
Output expected
[['q','1'], ['r','2'], ['s','3'], ['t','1'],['u','2'],['v','3'],['w','1'],['x','2'],['y','3'],
['z','1']]"
CodePudding user response:
This is a very simple approach to this problem.
lst1 = ['q','r','s','t','u','v','w','x','y','z']
lst2 = ['1','2','3']
new_list = []
for x in range(len(lst1)):
new_list.append([lst1[x], lst2[x % 3]])
print(new_list) # [['q', '1'], ['r', '2'], ['s', '3'], ['t', '1'], ['u', '2'], ['v', '3'], ['w', '1'], ['x', '2'], ['y', '3'], ['z', '1']]
You could also use list comprehension in this case, like so:-
new_list = [[lst1[x], lst2[x % 3]] for x in range(len(lst1))]
CodePudding user response:
You can use zip()
and itertools.cycle()
.
from itertools import cycle
lst1 = ['q','r','s','t','u','v','w','x','y','z']
lst2 =['1','2','3']
result = [[letter, number] for letter, number in zip(lst1, cycle(lst2))]
print(result)
Expected output:
[['q', '1'], ['r', '2'], ['s', '3'], ['t', '1'], ['u', '2'], ['v', '3'], ['w', '1'], ['x', '2'], ['y', '3'], ['z', '1']]
Another solution would be to additonally use map()
.
result = list(map(list, zip(lst1, cycle(lst2))))
In case you wanna use tuples you could just do
from itertools import cycle
lst1 = ['q','r','s','t','u','v','w','x','y','z']
lst2 =['1','2','3']
result = list(zip(lst1, cycle(lst2)))
print(result)
which would give you
[('q', '1'), ('r', '2'), ('s', '3'), ('t', '1'), ('u', '2'), ('v', '3'), ('w', '1'), ('x', '2'), ('y', '3'), ('z', '1')]