Python:根据整数之间的步长拆分整数列表
我有以下问题。有一个整数列表,我想把它分成一个列表,只要原始输入列表的两个元素之间的步长不是1。 例如:输入=[0,1,3,5,6,7],输出=[0,1],[3],[5,6,7]] 我写了下面的函数,但它非常糟糕,我想知道你们中是否有人能帮我找到更好的解决方案。我尝试使用itertools,但无法解决它 以下是我的解决方案:Python:根据整数之间的步长拆分整数列表,python,list,split,integer,indices,Python,List,Split,Integer,Indices,我有以下问题。有一个整数列表,我想把它分成一个列表,只要原始输入列表的两个元素之间的步长不是1。 例如:输入=[0,1,3,5,6,7],输出=[0,1],[3],[5,6,7]] 我写了下面的函数,但它非常糟糕,我想知道你们中是否有人能帮我找到更好的解决方案。我尝试使用itertools,但无法解决它 以下是我的解决方案: def _get_parts(list_of_indices): lv = list_of_indices tuples = zip(lv[:-1], lv
def _get_parts(list_of_indices):
lv = list_of_indices
tuples = zip(lv[:-1], lv[1:])
split_values = []
for i in tuples:
if i[1] - i[0] != 1:
split_values.append(i[1])
string = '/'.join([str(i) for i in lv])
substrings = []
for i in split_values:
part = string.split(str(i))
substrings.append(part[0])
string = string.lstrip(part[0])
substrings.append(string)
result = []
for i in substrings:
i = i.rstrip('/')
result.append([int(n) for n in i.split('/')])
return result
非常感谢 这适用于任何iterable
def _get_parts(i, step=1):
o = []
for x in i:
if o and o[-1] and x - step == o[-1][-1]:
o[-1].append(x)
else:
o.append([x])
return o
_get_parts([0, 1, 3, 5, 6, 7], step=1)
# [[0, 1], [3], [5, 6, 7]])
>>> from itertools import groupby, count
>>> inp = [0, 1, 3, 5, 6, 7]
>>> [list(g) for k, g in groupby(inp, key=lambda i,j=count(): i-next(j))]
[[0, 1], [3], [5, 6, 7]]
下面是一个利用for循环的解决方案
def splitbystep(alist):
newlist = [[alist[0]]]
for i in range(1,len(alist)):
if alist[i] - alist[i-1] == 1:
newlist[-1].append(alist[i])
else:
newlist.append([alist[i]])
return newlist
我会这样做:
inp = [0, 1, 3, 5, 6, 7]
base = []
for item in inp:
if not base or item - base[-1][-1] != 1: # If base is empty (first item) or diff isn't 1
base.append([item]) # Append a new list containing just one item
else:
base[-1].append(item) # Otherwise, add current item to the last stored list in base
print base # => [[0, 1], [3], [5, 6, 7]]
很好的解决方案。我认为这样的描述很有用:
j=count()
创建一个计数器。对next(j)
的每次调用都将以1步返回int。不明显的python行为:函数参数的默认值在函数创建时创建一次。因此,j
将仅用count()初始化一次,在下一次调用key
时,argj
将具有先前创建的实例groupby
将把inp
中具有相同键值的所有项追加到iterableg
中。如果键值已更改,则创建新的g。对于inp中的项目:项目=0,键=0-0=0;项目=1,键=1-1=0;项目=3,键=3-2=1;项目=5,键=5-3=2,依此类推。