简体   繁体   中英

Merging a list and a tuple in list

Suppose I have the following lists:

l1 = [['a','b','c'],['x','y','z'],['i','j','k']]
l2 = [(0,0.1),(0,0.2),(2,0.3),(2,0.4),(1,0.5),(0,0.6)]

I want to merge the two list on the keys of the l2 and index of l1 such that I get:

[[0.1,['a','b','c'],
[0.2,['a','b','c'],
[0.3,['i','j','k'],
[0.4,['i','j','k'],
[0.5,['x','y','z'],
[0.6,['a','b','c']]

I wonder how one does this? as the merge is not both on keys.

A list-comprehension with some indexing will do it nicely

l1 = [['a', 'b', 'c'], ['x', 'y', 'z'], ['i', 'j', 'k']]
l2 = [(0, 0.1), (0, 0.2), (2, 0.3), (2, 0.4), (1, 0.5), (0, 0.6)]

result = [[value, l1[idx]] for idx, value in l2]

The for loop equiv

result = []
for idx, value in l2:
    l1_item = l1[idx]
    result.append([value, l1_item])

A simple comprehension will do:

[[v, l1[i]] for i, v in l2]
# [[0.1, ['a', 'b', 'c']], 
#  [0.2, ['a', 'b', 'c']], 
#  [0.3, ['i', 'j', 'k']], 
#  [0.4, ['i', 'j', 'k']], 
#  [0.5, ['x', 'y', 'z']], 
#  [0.6, ['a', 'b', 'c']]]
l1 = [['a','b','c'],['x','y','z'],['i','j','k']]
l2 = [(0,0.1),(0,0.2),(2,0.3),(2,0.4),(1,0.5),(0,0.6)]

print([[v,l1[k]] for k,v in l2])

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM