如果索引在Python中超出范围或范围,是否有清晰的方法来获取列表索引或None
的值?
明显的做法是:
if len(the_list) > i:
return the_list[i]
else:
return None
但是,冗长会降低代码的可读性。是否有可以替代使用的干净,简单的单线?
答案 0 :(得分:32)
尝试:
try:
return the_list[i]
except IndexError:
return None
或者,一个班轮:
l[i] if i < len(l) else None
示例:
>>> l=range(5)
>>> i=6
>>> print(l[i] if i < len(l) else None)
None
>>> i=2
>>> print(l[i] if i < len(l) else None)
2
答案 1 :(得分:11)
我发现列表切片很适合:
>>> x = [1, 2, 3]
>>> a = x [1:2]
>>> a
[2]
>>> b = x [4:5]
>>> b
[]
因此,如果你想要x [i],总是访问x [i:i + 1]。如果存在,您将获得包含所需元素的列表。否则,您将获得一个空列表。
答案 2 :(得分:7)
return the_list[i] if len(the_list) > i else None
答案 3 :(得分:5)
出于您的目的,您可以排除else
部分,因为如果未满足给定条件,则默认返回None
。
def return_ele(x, i):
if len(x) > i: return x[i]
结果
>>> x = [2,3,4]
>>> b = return_ele(x, 2)
>>> b
4
>>> b = return_ele(x, 5)
>>> b
>>> type(b)
<type 'NoneType'>
答案 4 :(得分:5)
结合切片和迭代
next(iter(the_list[i:i+1]), None)
答案 5 :(得分:3)
如果您正在处理小型列表,则无需添加if语句或其他类型的列表。一个简单的解决方案是将列表转换为字典。然后,您可以使用dict.get
:
table = dict(enumerate(the_list))
return table.get(i)
您甚至可以使用None
的第二个参数设置另一个默认值而不是dict.get
。例如,如果索引超出范围,请使用table.get(i, 'unknown')
返回'unknown'
。
请注意,此方法不适用于负数索引。
答案 6 :(得分:0)
1.如果...否则...
l = [1, 2, 3, 4, 5]
for i, current in enumerate(l):
following = l[i + 1] if i + 1 < len(l) else None
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
2.尝试...除了...
l = [1, 2, 3, 4, 5]
for i, current in enumerate(l):
try:
following = l[i + 1]
except IndexError:
following = None
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
3.字典
适合小名单
l = [1, 2, 3, 4, 5]
dl = dict(enumerate(l))
for i, current in enumerate(l):
following = dl.get(i + 1)
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
4.列表切片
l = [1, 2, 3, 4, 5]
for i, current in enumerate(l):
following = next(iter(l[i + 1:i + 2]), None)
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
5. itertools.zip_longest
from itertools import zip_longest
l = [1, 2, 3, 4, 5]
for i, (current, following) in enumerate(zip_longest(l, l[1:])):
print(current, following)
# 1 2
# 2 3
# 3 4
# 4 5
# 5 None
使用 %%timeit
的 Jupyter 魔术命令
初始化
from itertools import zip_longest
l = list(range(10000000))
结果
方法 | 消费 |
---|---|
如果...否则... | 2.62 秒 |
尝试...除了... | 1.14 秒 |
字典 | 2.61 秒 |
列表切片 | 3.75 秒 |
itertools.zip_longest | 1.14 秒 |