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.
CodePudding user response:
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])
CodePudding user response:
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']]]
CodePudding user response:
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])