我有一个像这样的列表
mixed_list = [None, 1, 3, None, 5, 6, 7, 8, 10, None, None, 11, 12, None, None]
我需要找到此列表中的最后一个数字,其中连续的数字大于n
,在这种情况下为2
。所以...
输入:mixed_list
输出:10
我知道我必须编写一个循环,但是在此之后不知道如何开始。有人可以告诉我如何入门吗?
答案 0 :(得分:5)
首先尝试reverse
列表,然后从其开始iterating
标记找到的first number
,并在其后开始连续计数
If
在计数器大于None
之前得到n
,然后重置计数器,标记next number after None
并继续迭代。
Else
,您标记的号码是答案:)
下面的代码:
def find_the_number(the_list, n):
counter = 0
possible_answer = None
for i in reversed(the_list):
if i is not None:
if counter == 0:
possible_answer = i
counter += 1
else:
counter = 0
if counter > n:
return possible_answer
mixed_list = [None, 1, 3, None, 5, 6, 7, 8, 10, None, None, 11, 12, None, None]
cons_number = 2
print(find_the_number(mixed_list, cons_number))
答案 1 :(得分:2)
>>> next((v[-1] for v in reversed(list(zip(*[mixed_list[i:] for i in range(n+1)]))) if all(v)), None)
>>> 10
说明
zip(*[mixed_list[i:] for i in range(n+1)
将返回n + 1个连续的数字作为元组
>>> list(zip(*[mixed_list[i:] for i in range(n+1)]))
[(None, 1, 3), (1, 3, None), (3, None, 5), (None, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 10), (8, 10, None), (10, None, None), (None, None, 11), (None, 11, 12), (11, 12, None), (12, None, None)]
然后您将其反转
>>> list(reversed(list(zip(*[mixed_list[i:] for i in range(n+1)]))))
[(12, None, None), (11, 12, None), (None, 11, 12), (None, None, 11), (10, None, None), (8, 10, None), (7, 8, 10), (6, 7, 8), (5, 6, 7), (None, 5, 6), (3, None, 5), (1, 3, None), (None, 1, 3)]
然后,仅在元组包含所有数字时才对其进行过滤,并仅从元组中返回第一个数字
>>> [v[-1] for v in reversed(list(zip(*[mixed_list[i:] for i in range(n+1)]))) if all(v)]
[10, 8, 7]
您所要做的就是从返回的列表中获取第一个电话号码:)
答案 2 :(得分:1)
类似的事情应该起作用。 警告:未经测试,只需在此处输入
minimum_consecutives = 2
mixed_list = [None, 1, 3, None, 5, 6, 7, 8, 10, None, None, 11, 12, None, None]
consecutive_non_nulls = 0
last_item = None
for item in mixed_list:
if item is not None:
consecutive_non_nulls = consecutive_non_nulls + 1
else:
if consecutive_non_nulls > minimum_consecutives:
break;
consecutive_non_nulls = 0
last_item = item
print(last_item)
答案 3 :(得分:1)
我会在倒排的列表上使用itertools.groupby
。
from itertools import groupby
n = 2
lst = [None, 1, 3, None, 5, 6, 7, 8, 10, None, None, 11, 12, None, None]
groups = groupby(reversed(lst), lambda x: isinstance(x, int))
result = next((grplist[0] for p, grp in groups
for grplist in [list(grp)]
if p and len(grplist) > n), None)
答案 4 :(得分:1)
我接受了答案,但意识到他想念我,但由于Igor S,我修改了他的代码,这项工作奏效了。
def get_last_number2(list, n=2):
counter = 0
possible_answer = None
for i in list:
if i is not None:
possible_answer = i
counter +=1
else:
if counter>n:
return possible_answer
counter = 0