Python 3 压缩列表解包

标签 python python-3.x list zip python-3.4

<分区>

我有两个元组列表 mkp1mkp2zip 并想稍后将它们解压到列表中。但是在第一部分解压后,剩下的部分不见了……为什么?

最小的例子:

# list of tuples
mkp1 = [(1, 2), (3, 4), (5, 6)]
mkp2 = [(10, 20), (30, 40), (50, 60)]

# zip this list
pairs = zip(mkp1, mkp2)

# unzip this list
p1 = [kpp[0] for kpp in pairs]
p2 = [kpp[1] for kpp in pairs]
print('p1:', p1)
print('p2:', p2)

编辑:奇怪的是,这在 Python 2.7 中像我预期的那样工作,但在 Python 3.4 中却不是。

最佳答案

啊,我找到了 answer :在 Python 2 中,zip 返回一个元组列表,而在 Python 3 中它返回一个迭代器。这会导致第二次迭代生成一个空列表。

这个有效:

# list of tuples
mkp1 = [(1, 2), (3, 4), (5, 6)]
mkp2 = [(10, 20), (30, 40), (50, 60)]

# zip this list
pairs = zip(mkp1, mkp2)

# unzip this list
p1, p2 = [], []
for kpp in pairs:
    p1.append(kpp[0])
    p2.append(kpp[1])

print('p1:', p1)
print('p2:', p2)

关于Python 3 压缩列表解包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244823/

相关文章:

Python 正则表达式选择现在完成时的动词

python - 从 yaml 脚本动态创建嵌套函数

Python 等同于条件中类似 C 的赋值

python - Python中如何处理异常?

python-3.x - Python 读取文本中的字符直到出现空格

string - 用于获取字符串中每个字符的 ASCII 码的 Tcl

python - 高效地对 pandas 列的多个子集进行回归分析

python - 静音 OSX 崩溃报告窗口

python - Asyncio 和 aiohttp 将所有 url 路径路由到处理程序

python - 从函数列表中获取随机函数并调用所选函数