我正在处理许多行,根据当前行中的一个值x是否在上一行的值x的100以内对它们进行分组。
作为例子
5, "hello"
10, "was"
60, "bla"
5000, "qwerty""hello“、"was”和"bla“应该是一个组,另一个组是"qwerty”。
有什么办法可以用群比巧妙地解决这个问题吗?我能想到的所有解决方案都有点麻烦,比如每次调用groupby中的函数(键)时,都会使用带有先前值的dict默认参数,并更新它。
发布于 2015-04-26 08:12:43
您只需编写一个简单的类来封装临时变量,然后使用该类的一个方法作为关键函数:
class KeyClass(object):
def __init__(self):
self.lastValue = None
self.currentKey = 1
def handleVal(self, val):
if self.lastValue is not None and abs(val - self.lastValue) > 100:
self.currentKey += 1
self.lastValue = val
return self.currentKey
>>> [(k, list(g)) for k, g in itertools.groupby(data, KeyClass().handleVal)]
[(1, [1, 2, 100, 105]), (2, [300, 350, 375]), (3, [500]), (4, [800, 808])]为了好玩,我还想出了一种相当令人费解的方法,使用预高级生成器的send方法作为关键功能:
def keyGen():
curKey = 1
newVal = yield None
while True:
oldVal, newVal = newVal, (yield curKey)
if oldVal is None or abs(newVal-oldVal) > 100:
curKey += 1
key = keyGen()
next(key)
>>> [(k, list(g)) for k, g in itertools.groupby(data, key.send)]
[(1, [1, 2, 100, 105]), (2, [300, 350, 375]), (3, [500]), (4, [800, 808])]把你的头绕着看,这可能是理解.send的一个很好的练习(这是给我的!)
发布于 2015-04-26 07:29:09
itertools.groupby可能有一些巧妙的技巧,但是它非常简单,可以为您的特定问题编写一个自定义生成器函数。也许是这样的(未经测试的):
def grouper(it):
group = []
for item in it:
if not group or abs(int(item[0]) - int(group[-1][0])) < 100:
group.append(item)
else:
yield group
group = [item]
if group: # yield final group if not empty
yield group使用方式类似于
with open(filename) as fid:
for group in grouper(line.split(',') for line in fid):
# do something with group
for item in group:
# do something with itemhttps://stackoverflow.com/questions/29874889
复制相似问题