gpt4 book ai didi

python - 元组列表中的高效搜索

转载 作者:太空宇宙 更新时间:2023-11-03 18:32:11 25 4
gpt4 key购买 nike

我想在列表上搜索,如果找到则获取其补集

例如:

l = [('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd')]


get_adjunct('1')

输出

# u'a'

我知道这样:

def search_adjunct(search)
for item in list:
if item[0] == search:
return item[1]
return search

有人知道其他简单有效的方法吗?

最佳答案

以下内容:

l = [('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd')]
d = dict(l)
d['1']
# 'a'

如果没有字典,生成器会给你:

next((item[1] for item in l if item[0] == search), None)

next 如果生成器为空,则返回第二个参数(无)

关于python - 元组列表中的高效搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22233613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com