简体   繁体   中英

Python returns an element of sublist if the given element present in that sublist

How to make the python returns this:

list = [['a', 23, 'h401'], ['f', 45, 'h403'], ['g', 56, 'h401']]

If 'h401' is given as an input, it should return the total of numbers in the index of [1] of sublists with 'h401'

>>> 79                 #(23 + 56)

same as if 'h403 ' is given it should return the [1] of sublist with 'h403' which is 45

You can use an expression to select the second element only if your third element is h401 and sum them.

l = [['a', 23, 'h401'], ['f', 45, 'h403'], ['g', 56, 'h401']]

sum(i[1] for i in l if i[2] == 'h401')

If you just want to check for your target element to be in the list, you can use:

sum(i[1] for i in l if 'h401' in i)
inp = input("input code")
mlist = [['a', 23, 'h401'], ['f', 45, 'h403'], ['g', 56, 'h401']]
count = 0
for i in range (len(mlist)):
    if (mlist[i][2] == inp):
        count += mlist[i][1]

print(count)

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