繁体   English   中英

如果给定元素存在于子列表中,则Python返回该子列表的元素

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

如何使python返回以下内容:

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

如果输入'h401' ,则应返回带有'h401'的子列表的索引[1]'h401'

>>> 79                 #(23 + 56)

与给定'h403 '相同,它应返回'h403'45的子列表的[1]

仅当第三个元素为h401并对它们求和时,才可以使用表达式选择第二个元素。

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

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

如果只想检查目标元素是否在列表中,则可以使用:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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