Python:创建元组列表的优雅方式?

时间:2012-09-29 17:47:50

标签: python

>>> a=["a"]*4
>>> a
['a', 'a', 'a', 'a']
>>> b=range(4)
>>> b
[0, 1, 2, 3]
>>> c = [range(4,8), range(9,13), range(14,18), range(19,23)]
>>> c
[[4, 5, 6, 7], [9, 10, 11, 12], [14, 15, 16, 17], [19, 20, 21, 22]]
>>>
>>> result = map(lambda x,y:[x,y],a,b)
>>> map(lambda x,y:x.extend(y),result,c)
>>> result = map(tuple, result)
>>> result     # desired output: 
[('a', 0, 4, 5, 6, 7), ('a', 1, 9, 10, 11, 12), ('a', 2, 14, 15, 16, 17), ('a', 3, 19, 20, 21, 22)]
>>>
>>> try_test = zip(a,b,c)
>>> try_test # NOT DESIRED: leaves me with the list within the tuples
[('a', 0, [4, 5, 6, 7]), ('a', 1, [9, 10, 11, 12]), ('a', 2, [14, 15, 16, 17]), ('a', 3, [19, 20, 21, 22])]

我想知道是否有人有更简洁的方法来做“结果”?

3 个答案:

答案 0 :(得分:6)

您可以尝试这样的事情:

result = [tuple([ai, bi] + ci) for ai, bi, ci in zip(a, b, c)]

答案 1 :(得分:2)

对于此问题的完全一般方法,您可以考虑使用flatten上的众多变体之一,您可以找到here,其中flatten是一个任意嵌套的函数可迭代的迭代,并返回其中包含的项目的平面列表。

然后只需将flatten映射到a, b, c的压缩值并转换为元组。

>>> from collections import Iterable
>>> def flatten(l):
...     for i in l:
...         if isinstance(i, Iterable) and not isinstance(i, basestring):
...             for sub in flatten(i):
...                 yield sub
...         else:
...             yield i
...
>>> map(tuple, map(flatten, zip(a, b, c)))
[('a', 0, 4, 5, 6, 7), ('a', 1, 9, 10, 11, 12), 
 ('a', 2, 14, 15, 16, 17), ('a', 3, 19, 20, 21, 22)]

或者甚至更简洁,修改flatten以接受任意参数列表并返回元组。那么你所需要的只是map

>>> def flat_tuple(*args):
...     return tuple(flatten(args))
... 
>>> map(flat_tuple, a, b, c)
[('a', 0, 4, 5, 6, 7), ('a', 1, 9, 10, 11, 12), 
 ('a', 2, 14, 15, 16, 17), ('a', 3, 19, 20, 21, 22)]

如果这是一次性问题,上述方法可能比它的价值更麻烦。但是,如果您已经为其他目的定义了flatten,或者如果您经常这样做,以上可以为您节省很多麻烦!

否则,只是为了它的乐趣,这里是nneonneo的答案的变体,我喜欢:

>>> [x + tuple(y) for x, y in zip(zip(a, b), c)]
[('a', 0, 4, 5, 6, 7), ('a', 1, 9, 10, 11, 12), 
 ('a', 2, 14, 15, 16, 17), ('a', 3, 19, 20, 21, 22)]

答案 2 :(得分:-2)

对于这种情况:(如果简洁==短)

q = lambda x : tuple(range(x,x+4))
res = [ ('a', num) + q(4*(num+1)+num) for num in xrange(4) ]