给定任何类型(列表/字符串/范围)的输入序列,如何在输入中找到指定项目之后的下一个项目?
此外,如果该项目不存在或后面没有任何内容,则该函数应返回None
。
我尝试将输入类型转换为列表,然后从列表中查找位置,然后获取下一个项目,但这并不适用于所有输入类型。我写了一些东西,但我知道它不是Pythonic,而且它也会超时。(codewars挑战:https://www.codewars.com/kata/542ebbdb494db239f8000046/train/python)
我的尝试:
def next_item(xs, item):
xs_list = list(xs)
if item in xs_list:
position = xs_list.index(item)
try:
return xs_list[position+1]
except IndexError:
return None
else:
return None
Run Code Online (Sandbox Code Playgroud)
期望的结果:
next_item([1, 2, 3, 4, 5, 6, 7, 8], 5)
# 6)
next_item(['a', 'b', 'c'], 'd')
# None)
next_item(['a', 'b', 'c'], 'c')
# None)
next_item('testing', 't')
# # 'e')
next_item(iter(range(1, 3000)), 12)
# , 13)
Run Code Online (Sandbox Code Playgroud)
简单的解决方案:
def next_item(xs, item):
it = iter(xs)
item in it
return next(it, None)
Run Code Online (Sandbox Code Playgroud)
尝试item in it
查找该项目,从而消耗该迭代器,直到找到该项目或到达末尾。
您可以使用next返回指定元素之后的元素:
def next_item(seq, e):
iterable = iter(seq)
for i in iterable:
if i == e:
return next(iterable, None)
return None
print(next_item([1, 2, 3, 4, 5, 6, 7, 8], 5))
print(next_item(['a', 'b', 'c'], 'd'))
print(next_item(['a', 'b', 'c'], 'c'))
print(next_item('testing', 't'))
print(next_item(iter(range(1, 3000)), 12))
Run Code Online (Sandbox Code Playgroud)
输出
6
None
None
e
13
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
150 次 |
最近记录: |