1

我有一个元组序列,例如:

[(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()),但我只得到了拆分序列的第一个元组。我怎样才能做到这一点?

4

5 回答 5

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)]]
于 2013-09-12T11:50:39.040 回答
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
于 2013-09-12T13:34:26.143 回答
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)]]
于 2013-09-12T12:04:13.167 回答
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)]]
于 2013-10-08T10:34:12.777 回答
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)]]
于 2013-09-12T12:03:17.863 回答