我是新来的Python,我想编写一个函数,组列出与None
信号延续项目,像这样的项目:列表中的“延续”项目。在itertools groupby关键函数中存储状态不好?
>>> g([1, None, 1, 1, None, None, 1])
[[1, None], [1], [1, None, None], [1]]
我的真实数据有更复杂的项目,但我已经简化了这个问题的核心。
这是我的解决方案迄今:
import itertools
# input
x = [1, None, 1, 1, None, None, 1]
# desired output from g(x)
y = [[1, None], [1], [1, None, None], [1]]
def f(x):
if x is None:
f.lastx = x
else:
if x != f.lastx:
f.counter += 1
return f.counter
def g(x):
f.lastx = None
f.counter = 0
z = [list(g) for _, g in itertools.groupby(x, f)]
return z
assert y == g(x)
这工作,但我知道这是非常难看。
有没有更好的(更Pythonic)方法来做到这一点?例如。没有状态键功能。
哇,这是一些密集的代码。 :)我花了一些时间来了解它的工作原理,但我喜欢它,并且可以看到这种方法相当灵活。 –
实际上,我只是注意到了一些......这种方法需要2遍以上的输入数据。如果数据流式传输(因为它是我的更大的问题),那么这种方法是行不通的。 :( –
@BrianG:那么你不应该说你是分组*列表*项目。;-)但是处理一个流也很容易。 – DSM