4
>>> 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])]

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

4

3 回答 3

6

你可以尝试这样的事情:

result = [tuple([ai, bi] + ci) for ai, bi, ci in zip(a, b, c)]
于 2012-09-29T17:51:19.153 回答
2

对于此问题的完全通用方法,您可以考虑使用flatten您可以在此处找到的众多变体之一,其中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)]
于 2012-09-29T18:29:28.250 回答
-2

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

q = lambda x : tuple(range(x,x+4))
res = [ ('a', num) + q(4*(num+1)+num) for num in xrange(4) ]
于 2012-09-29T18:00:25.497 回答