我有一个由2个元素的元组列表,我想将它们转换成2个列表,其中第一个列表包含每个元组中的第一个元素,第二个列表包含第二个元素。
例如:
original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
有没有内置函数可以做到这一点?
zip
是自己的反函数!只要使用特殊的*运算符。>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
zip
函数:zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))
zip
(在转换为元组后),否则不必担心参数数量过多。zip
返回一个惰性迭代器,但这很容易转换:>>> list(zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]))
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
zip([], [])
并不能得到[], []
,而只是得到了[]
。如果事情能够这么简单就好了…… - user2357112zip
在 Python 3 中的工作方式完全相同,只是返回一个迭代器而不是列表。为了获得与上面相同的输出,您只需要将 zip
调用包装在列表中:list(zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]))
将输出 [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
。 - MJeffryeslist
是可以的。但是如果您尝试一次性实现全部结果(通过将zip
的结果转换为list
),则可能会使用大量内存(因为必须立即创建所有 tuple
)。如果您只能在不进行list
转换的情况下迭代zip
的结果,则可以节省大量内存。唯一的其他问题是如果输入具有许多元素;成本在于必须将它们全部解包为参数,并且zip
将需要为它们创建和存储迭代器。这仅在非常长的list
(想象成数十万个或更多元素)中才是真正的问题。 - ShadowRanger你也可以这样做
result = ([ a for a,b in original ], [ b for a,b in original ])
它应该能更好地扩展。特别是如果Python不需要时不扩展列表推导。
(顺便提一下,它生成了一个包含两个列表的2元组(对),而不像zip
那样生成一个元组列表。)
如果使用生成器而不是实际的列表可以的话,可以这样做:
result = (( a for a,b in original ), ( b for a,b in original ))
生成器在你要求每个元素之前不会遍历整个列表,但另一方面,它们会保留对原始列表的引用。
zip(*x)
更好。zip(*x)
只需要一次循环,而且不会使用堆栈元素。 - habnabitzip
更好。 - Liz Av我喜欢在我的程序中使用zip(*iterable)
(这正是你正在寻找的代码片段),示例:
def unzip(iterable):
return zip(*iterable)
我认为unzip
更易读。
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
但是对于长度不同的列表,zip
函数会将每个元素截断为最短列表的长度:
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])
[('a', 'b', 'c', 'd', 'e')]
你可以使用不带函数的map来将空结果填充为None:
>>> map(None, *[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )])
[('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)]
不过,zip()稍微快一点。
izip_longest
。 - Marcinzip_longest
。 - zezollo为了获得一个列表的元组,就像问题中所示:
>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple([list(tup) for tup in zip(*original)])
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])
将这两个列表解包成单独的变量:
list1, list2 = [list(tup) for tup in zip(*original)]
def transpose_finite_iterable(iterable):
return zip(*iterable) # `itertools.izip` for Python 2 users
对于有限可迭代对象(例如序列,如list
/tuple
/str
),它能正常工作,其元素可以是潜在的无限可迭代对象,可以用以下方式说明:
| |a_00| |a_10| ... |a_n0| |
| |a_01| |a_11| ... |a_n1| |
| |... | |... | ... |... | |
| |a_0i| |a_1i| ... |a_ni| |
| |... | |... | ... |... | |
其中
n
是自然数集合中的元素,a_ij
对应于第 i
个可迭代对象中的第 j
个元素,应用 transpose_finite_iterable
后,我们得到
| |a_00| |a_01| ... |a_0i| ... |
| |a_10| |a_11| ... |a_1i| ... |
| |... | |... | ... |... | ... |
| |a_n0| |a_n1| ... |a_ni| ... |
a_ij == j
,n == 2
。>>> from itertools import count
>>> iterable = [count(), count()]
>>> result = transpose_finite_iterable(iterable)
>>> next(result)
(0, 0)
>>> next(result)
(1, 1)
transpose_finite_iterable
来返回原始iterable
的结构,因为result
是一个无限可迭代的有限迭代器(在我们的情况下是元组)。>>> transpose_finite_iterable(result)
... hangs ...
Traceback (most recent call last):
File "...", line 1, in ...
File "...", line 2, in transpose_finite_iterable
MemoryError
那么我们该如何处理这种情况呢?
deque
在查看itertools.tee
函数的文档后,有一个Python配方可以在进行一些修改后帮助我们解决这个问题。
def transpose_finite_iterables(iterable):
iterator = iter(iterable)
try:
first_elements = next(iterator)
except StopIteration:
return ()
queues = [deque([element])
for element in first_elements]
def coordinate(queue):
while True:
if not queue:
try:
elements = next(iterator)
except StopIteration:
return
for sub_queue, element in zip(queues, elements):
sub_queue.append(element)
yield queue.popleft()
return tuple(map(coordinate, queues))
让我们检查一下
>>> from itertools import count
>>> iterable = [count(), count()]
>>> result = transpose_finite_iterables(transpose_finite_iterable(iterable))
>>> result
(<generator object transpose_finite_iterables.<locals>.coordinate at ...>, <generator object transpose_finite_iterables.<locals>.coordinate at ...>)
>>> next(result[0])
0
>>> next(result[0])
1
现在我们可以使用functools.singledispatch
装饰器定义通用函数,用于处理包含有限迭代和潜在无限迭代的可迭代对象。
from collections import (abc,
deque)
from functools import singledispatch
@singledispatch
def transpose(object_):
"""
Transposes given object.
"""
raise TypeError('Unsupported object type: {type}.'
.format(type=type))
@transpose.register(abc.Iterable)
def transpose_finite_iterables(object_):
"""
Transposes given iterable of finite iterables.
"""
iterator = iter(object_)
try:
first_elements = next(iterator)
except StopIteration:
return ()
queues = [deque([element])
for element in first_elements]
def coordinate(queue):
while True:
if not queue:
try:
elements = next(iterator)
except StopIteration:
return
for sub_queue, element in zip(queues, elements):
sub_queue.append(element)
yield queue.popleft()
return tuple(map(coordinate, queues))
def transpose_finite_iterable(object_):
"""
Transposes given finite iterable of iterables.
"""
yield from zip(*object_)
try:
transpose.register(abc.Collection, transpose_finite_iterable)
except AttributeError:
# Python3.5-
transpose.register(abc.Mapping, transpose_finite_iterable)
transpose.register(abc.Sequence, transpose_finite_iterable)
transpose.register(abc.Set, transpose_finite_iterable)
这可以被视为在有限非空可迭代对象的二元运算符类中,其自身的反演(数学家称这种函数为"反演函数")。
singledispatch
的额外奖励,我们可以像处理其他对象一样处理 numpy
数组。import numpy as np
...
transpose.register(np.ndarray, np.transpose)
>>> array = np.arange(4).reshape((2,2))
>>> array
array([[0, 1],
[2, 3]])
>>> transpose(array)
array([[0, 2],
[1, 3]])
transpose
返回的是迭代器,如果有人想要一个类似于OP中list
的tuple
,可以使用 map
内置函数 进一步实现。
>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple(map(list, transpose(original)))
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])
我已经在 0.5.0
版本的lz
包中添加了通用解决方案,可以像下面这样使用:
>>> from lz.transposition import transpose
>>> list(map(tuple, transpose(zip(range(10), range(10, 20)))))
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (10, 11, 12, 13, 14, 15, 16, 17, 18, 19)]
对于可能是无限的可迭代对象,以及其中可能包含无限的可迭代对象的情况,目前没有解决方案(至少没有显而易见的)。不过这种情况相对较少出现。
这只是另一种方法,但它帮助了我很多,所以我在这里写下来:
有了这个数据结构:
X=[1,2,3,4]
Y=['a','b','c','d']
XY=zip(X,Y)
In: XY
Out: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
x,y=zip(*XY)
x,y=(list(x),list(y))
考虑使用 more_itertools.unzip:
>>> from more_itertools import unzip
>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> [list(x) for x in unzip(original)]
[['a', 'b', 'c', 'd'], [1, 2, 3, 4]]
之前的回答都没有有效地提供所需的输出,即列表元组而不是元组列表。对于前者,您可以使用map
和tuple
。这是区别:
res1 = list(zip(*original)) # [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
res2 = tuple(map(list, zip(*original))) # (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
zip
返回一个列表而不是迭代器。list
或tuple
的函数以耗尽迭代器。对于内存效率较高的迭代器,您可以省略相应解决方案的外部list
和tuple
调用。虽然numpy数组和pandas可能更好,但当作为unzip(args)
调用时,此函数模拟了zip(*args)
的行为。
允许生成器(例如Python 3中zip
的结果)作为args
传递,因为它遍历值。
def unzip(items, cls=list, ocls=tuple):
"""Zip function in reverse.
:param items: Zipped-like iterable.
:type items: iterable
:param cls: Container factory. Callable that returns iterable containers,
with a callable append attribute, to store the unzipped items. Defaults
to ``list``.
:type cls: callable, optional
:param ocls: Outer container factory. Callable that returns iterable
containers. with a callable append attribute, to store the inner
containers (see ``cls``). Defaults to ``tuple``.
:type ocls: callable, optional
:returns: Unzipped items in instances returned from ``cls``, in an instance
returned from ``ocls``.
"""
# iter() will return the same iterator passed to it whenever possible.
items = iter(items)
try:
i = next(items)
except StopIteration:
return ocls()
unzipped = ocls(cls([v]) for v in i)
for i in items:
for c, v in zip(unzipped, i):
c.append(v)
return unzipped
使用列表容器,只需运行unzip(zipped)
,如下所示:
unzip(zip(["a","b","c"],[1,2,3])) == (["a","b","c"],[1,2,3])
要使用双端队列或其他支持 append
的容器,需要传递一个工厂函数。
from collections import deque
unzip([("a",1),("b",2)], deque, list) == [deque(["a","b"]),deque([1,2])]
(装饰cls
和/或main_cls
以微调容器初始化,如上面最终的断言语句中所示。)
d=dict(original)
后跟d.keys()
和d.values()
可能很方便。 - djvg