from a list of numbers how can I go through the list by taking five numbers for iteration and placing the first two as variables and the last three inside a tuple? i have the list
['20','15','45','76','0','67','45','485','16','8']
i want a = 20 , b = 15 and t = ('45','76','0')
then i want a = 67 , b = 45 and t = ('485','16','8') and put them into a list.
as a result I would have
[['20','15',('45','76','0')],['67','45',('485','16','8')]]
i really don't know how iterate 5 items every time
CodePudding user response:
>>> l = ['20','15','45','76','0','67','45','485','16','8']
>>>
>>> for k in range(0,len(l),5):
... print(l[k], l[k 1], l[k 2:k 5])
20 15 ['45', '76', '0']
67 45 ['485', '16', '8']
>>>
CodePudding user response:
You can use a simple list comprehension:
l = ['20','15','45','76','0','67','45','485','16','8']
N = 5
[[l[i],l[i 1],tuple(l[i 2:i 5])]for i in range(0, len(l), N)]
output:
[['20', '15', ('45', '76', '0')],
['67', '45', ('485', '16', '8')]]