给定任何类型(列表/字符串/范围)的输入序列,如何在输入中找到指定项目之后的下一个项目?
此外,如果该项目不存在或后面没有任何内容,则该函数应返回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) 返回第 N 个偶数(想象一个偶数列表,返回输入数字在人眼位置的数字)
示例(输入 --> 输出)
1 --> 0 (the first even number is 0)
3 --> 4 (the 3rd even number is 4 (0, 2, 4))
Run Code Online (Sandbox Code Playgroud)
(nth_even(3), --> 4)
(nth_even(1), --> 0)
(nth_even(2), --> 2)
(nth_even(100), --> 198)
(nth_even(1298734), --> 2597466)
Run Code Online (Sandbox Code Playgroud)
我的代码在处理更大的数字时超时,所以我需要一个更快的方法。
def nth_even(n):
data = [num for num in range(0, n*2) if num % 2 == 0]
return data[n-1]
Run Code Online (Sandbox Code Playgroud)