She*_*man 6 python integer list
我试图从未排序的列表中找到连续的值。实验代码如下:
num = [8, 9, 4, 1, 2, 3]
#(num[0+1]) next value
for i in range(len(num)-1): # not using -1 will cause index error
if num[i]+1==num[i+1]:
print('Con',num[i])
Run Code Online (Sandbox Code Playgroud)
问题:我无法使用当前代码获取最后一个值。我的输出不包括最后一个值。这是我得到的(9 号或 3 号):
Con 8
Con 1
Con 2
Run Code Online (Sandbox Code Playgroud)
我见过一些复杂的解决方案,对我来说有点难以理解。是否可以稍微调整 for 循环部分并获得整个序列?多谢。
您可以使用该功能groupby
:
from itertools import groupby\n\nnum = [8, 9, 4, 1, 2, 3]\n\n# Enumerate and get differences between counter\xe2\x80\x94integer pairs\n# Group by differences (consecutive integers have equal differences) \ngb = groupby(enumerate(num), key=lambda x: x[0] - x[1])\n\n# Repack elements from each group into list\nall_groups = ([i[1] for i in g] for _, g in gb)\n\n# Filter out one element lists\nlist(filter(lambda x: len(x) > 1, all_groups))\n# [[8, 9], [1, 2, 3]]\n
Run Code Online (Sandbox Code Playgroud)\n
这是因为您只检查下一个数字。当您想要第二个数字(例如 9 或 3)时,您还必须勾选前一个数字。这会使时间if
更长一点,但它会起作用。
num=[8,9,4,1,2,3]
for i in range(len(num)):
if (
( # check for the next number
i + 1 != len (num) and # don't check the end of the list
num[i]+1==num[i+1]
) or ( # check for the previous number
i != 0 and # don't check before the list
num [i-1] == num [i] - 1
)
): print('Con',num[i])
Run Code Online (Sandbox Code Playgroud)
另外,我必须删除-1
您范围内的 ,因为我已经进行了手动检查,并且正如所指出的,这阻止了 3 的显示。