Rajdeep Siddhapura
Rajdeep Siddhapura

Reputation: 933

Python code to access sub-List by index of first element of that sub-List

I have 2 lists in following format:

list1 = [[[a, b], 0.2], [[a, c], 0.5], [[a, d], 0.3], [[b, d], 0.1]]
# list1 is sorted by first element of its sublist

list2 = [[a, b], [a, d], [b, d]]
# list2 is sorted

I want SUM of all 'second elements of sublist of list1' corresponding to each element in list2

therefore sum should be 0.2 + 0.3 + 0.1 = 0.6

note : elements in subsets always exists in list1

My solution:

list11=[]
list12=[] 
for i in list1:
    list11.append(i[0])
    list12.append(i[1])

sum=0

for i in list2:
    sum+=list12[list11.index(i)]

I hope there is a solution that does not involve creating temporary lists.

Upvotes: 0

Views: 1963

Answers (1)

karthikr
karthikr

Reputation: 99680

You can use a list comprehension to achieve this:

x = [['a', 'b'], ['a', 'd'], ['b', 'd']]
y = [[['a', 'b'], 0.2], [['a', c], 0.5], [['a', 'd'], 0.3], [['b', 'd'], 0.1]]
total = sum([b for a, b in y if a in x])

Demo

>>> x = [['a','b'], ['a', 'd'], ['b', 'd']]
>>> y = [[['a', 'b'], 0.2], [['a', 'c'], 0.5], [['a', 'd'], 0.3], [['b', 'd'], 0.1]]
>>> [b for a, b in y if a in x]
[0.2, 0.3, 0.1]
>>> sum([b for a, b in y if a in x])
0.6

Upvotes: 3

Related Questions