I have a list of tuples which comprise of a string and another list;
[('string1', ['a1', 'b1']),
('string2', ['a2', 'b2']),
('string3', ['a3', 'b3'])]
I cannot figure out using list comprehension to arrive at something like;
[['string1a1', 'string1b1'],
['string2a2', 'string2b2'],
['string3a3', 'string3b3']]
I tried something like
results = [join(ministring, i) for i in (miniarray for (ministring, miniarray) in myarray)]
but i am confused at each variables scope within the expansion/expression(?).
As simple as that:
lst = [('string1', ['a1', 'b1']),
('string2', ['a2', 'b2']),
('string3', ['a3', 'b3'])]
res = [[master + tail for tail in sublist] for master, sublist in lst]
which returns:
[['string1a1', 'string1b1'], ['string2a2', 'string2b2'], ['string3a3', 'string3b3']]
Note that with this approach the length of the sublist inside the tuple is not fixed. It can be arbitrarily long.
You could do something like this:
data = [('string1', ['a1', 'b1']),
('string2', ['a2', 'b2']),
('string3', ['a3', 'b3'])]
result = [[s + e1, s + e2] for s, [e1, e2] in data]
print(result)
Output
[['string1a1', 'string1b1'], ['string2a2', 'string2b2'], ['string3a3', 'string3b3']]
Note that this assumes the inner list have only two elements.
尝试这个:
new_list = list(map(lambda x: [x[0]+x[1][0], x[0]+x[1][1]],data))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.