Reputation: 9
I have a list below. I need to use it to create a new nested list with only the first element in the sublist with the last element in list.
a=[[a,b,c],3]
the outcome should look like
b=[[a,3],[b,3],[c,3]]
Upvotes: 0
Views: 65
Reputation: 107287
Use zip()
:
In [79]: a=[['a','b','c'],3]
In [80]: list(zip(a[0], [a[1]]*len(a[0])))
Out[80]: [('a', 3), ('b', 3), ('c', 3)]
Or:
In [83]: (a, b, c), num = a
In [84]: [(a, num), (b, num), (c, num)]
Out[84]: [('a', 3), ('b', 3), ('c', 3)]
Or more general:
In [85]: lst, num = a
In [86]: from itertools import repeat
In [87]: list(zip(lst, repeat(num, len(lst))))
Out[87]: [('a', 3), ('b', 3), ('c', 3)]
Another way is using a nested list comprehension:
In [15]: a
Out[15]: [['a', 'b', 'c'], [1, 2]]
In [16]: [(j, i) for i in a[1] for j in a[0]]
Out[16]: [('a', 1), ('b', 1), ('c', 1), ('a', 2), ('b', 2), ('c', 2)]
Upvotes: 1
Reputation: 43126
You can use a list comprehension:
>>> a = [['a','b','c'], 3]
>>> sublist, value = a
>>> [[x, value] for x in sublist]
[['a', 3], ['b', 3], ['c', 3]]
Upvotes: 1