2024-04-26 08:00:03 发布
网友
请问,测试某个简单变量X是否在列表(或元组)中的“终极Python”方法是什么?如果为真,那么从同一位置的另一个列表(或元组)返回值?字典会更好用吗?你知道吗
list.index()或tuple.index()方法返回匹配值的第一个索引:
list.index()
tuple.index()
def mapped_value(somelist, someotherlist, value): try: index = somelist.index(value) except ValueError: return None return someotherlist[index]
如果value不存在,则引发ValueError,此时返回None。你知道吗
value
ValueError
None
通过捕捉IndexError,可以使其更加紧凑,并防止较短的someotherlist:
IndexError
someotherlist
def mapped_value(somelist, someotherlist, value): try: return someotherlist[somelist.index(value)] except (ValueError, IndexError): return None
但是,将值映射到其他值的字典会更方便,是的。您可以使用以下工具将两个列表转换为词典:
mapping = dict(zip(somelist, someotherlist)) return mapping.get(value)
其中假定somelist中的项是唯一的和可散列的。你知道吗
somelist
演示:
>>> somelist = ['foo', 'bar', 'baz'] >>> someotherlist = ['spam', 'ham', 'eggs'] >>> mapped_value(somelist, someotherlist, 'bar') 'ham' >>> mapping = dict(zip(somelist, someotherlist)) >>> mapping.get('bar') 'ham'
list.index()
或tuple.index()
方法返回匹配值的第一个索引:如果
value
不存在,则引发ValueError
,此时返回None
。你知道吗通过捕捉
IndexError
,可以使其更加紧凑,并防止较短的someotherlist
:但是,将值映射到其他值的字典会更方便,是的。您可以使用以下工具将两个列表转换为词典:
其中假定
somelist
中的项是唯一的和可散列的。你知道吗演示:
相关问题 更多 >
编程相关推荐