Die*_*ero 1 python list python-3.x
挑战是在 python 中找到第一个非连续数字。我已经成功地使用一个名为 more_itertools 的库来做到这一点,但挑战要求不涉及任何库。我该如何解决?这是我的代码:
from more_itertools import consecutive_groups
def first_non_consecutive(l):
g = []
for grp in consecutive_groups(l):
g.append(list(grp))
if len(g) > 1:
return g[1][0]
Run Code Online (Sandbox Code Playgroud)
在这里使用enumeratewithstart参数对你有利。
def first_non_consecutive(lst):
for i, j in enumerate(lst, lst[0]):
if i!=j:
return j
first_consecutive([1,2,3,4,6,7,8])
# 6
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3455 次 |
| 最近记录: |