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

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

最佳答案

对于此问题的完全通用方法,您可以考虑使用 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)]

如果这是一次性问题,上述方法可能会比它的值(value)更麻烦。但是,如果您已经为其他目的定义了 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)]

关于Python:创建元组列表的优雅方式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12655007/

10-12 04:28