如何根据谓词拆分元组的Python序列?

时间:2013-09-12 11:44:08

标签: python split sequence

我有一系列元组,例如:

[(0.0, 0.25), (0.25, 0.25), (0.5, 0.5), (1.0, 0.25), (1.25, 0.75), (2.0, 1.0)]

我想以这样的方式拆分这个序列,即拆分序列的第一个元组的第一个元素是一个整数:

[[(0.0, 0.25), (0.25, 0.25), (0.5, 0.5)],
 [(1.0, 0.25), (1.25, 0.75)],
 [(2.0, 1.0)]]

我试着用filter(sequence, lambda x: x[0].is_integer())写一些东西,但我只得到了分裂序列的第一个元组。 我怎么能这样做?

5 个答案:

答案 0 :(得分:1)

这是否可以按你的要求工作?

>>> testList = [(0.0, 0.25), (0.25, 0.25), (0.5, 0.5), (1.0, 0.25), (1.25, 0.75), (2.0, 1.0)]
>>> from operator import itemgetter
>>> testList.sort(key=itemgetter(0)) # Making sure it is sorted. If list is pre-sorted, skip this step.
>>> from itertools import groupby
>>> final_list = [list(lst) for _, lst in groupby(testList, lambda x: int(x[0]))]
>>> from pprint import pprint
>>> pprint(final_list)
[[(0.0, 0.25), (0.25, 0.25), (0.5, 0.5)],
 [(1.0, 0.25), (1.25, 0.75)],
 [(2.0, 1.0)]]

答案 1 :(得分:1)

对于像我这样的任何傻瓜;)

a = [(0.0, 0.25), (0.25, 0.25), (0.5, 0.5), (1.0, 0.25), (1.25, 0.75), (2.0, 1.0)]
key, value = zip(*a)

index = 0
output = []
index_dict = {}
for i in range(0, len(key)):
    k, v = key[i], value[i]
    if int(k) in index_dict:
            output[index_dict[int(k)]].append((k, v))
    else:
            index_dict[int(k)] = index
            output.append([(k, v)])
            index += 1

答案 2 :(得分:0)

我假设第一个元组的第一个元素是整数。

您可以使用reduce()函数在一行中解决它并单次传递列表:

>>> l = [(0.0, 0.25), (0.25, 0.25), (0.5, 0.5), (1.0, 0.25), (1.25, 0.75), (2.0, 1.0)]
>>> reduce(lambda acc, x: acc + [[x]] if x[0].is_integer() else acc[:-1] + [acc[-1] + [x]], l, [])
[[(0.0, 0.25), (0.25, 0.25), (0.5, 0.5)], 
[(1.0, 0.25), (1.25, 0.75)], 
[(2.0, 1.0)]]

答案 3 :(得分:0)

这很直接,并不那么漂亮,但有效:

from itertools import takewhile
from pprint import pprint


l = [(0.0, 0.25), (0.25, 0.25), (0.5, 0.5), (1.0, 0.25), (1.25, 0.75), (2.0, 1.0)]

result = []
i = 0
while i < len(l):
    item = [l[i]] + list(takewhile(lambda x: x[0] % 1, l[i + 1:]))
    result.append(item)
    i += len(item)

pprint(result)

打印:

[[(0.0, 0.25), (0.25, 0.25), (0.5, 0.5)],
 [(1.0, 0.25), (1.25, 0.75)],
 [(2.0, 1.0)]]

答案 4 :(得分:0)

使用collections.defaultdict,您可以轻松完成此操作而不会失去可更正性

>>> from collections import defaultdict
>>> some_list = [(0.0, 0.25), (0.25, 0.25), (0.5, 0.5), (1.0, 0.25), (1.25, 0.75), (2.0, 1.0)]
>>> accum = defaultdict(list)
>>> for e in some_list:
    accum[int(e[0])].append(e)


>>> import pprint
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(accum.values())
[   [(0.0, 0.25), (0.25, 0.25), (0.5, 0.5)],
    [(1.0, 0.25), (1.25, 0.75)],
    [(2.0, 1.0)]]