元组提取的python元组

标签 python list-comprehension iterable-unpacking

假设您有以下元组的元组:

test = ((1, '2'), (3, '4'), ('5', '6'))

如果我想提取每个元组的第二个元素,我会这样做:

secondonly = tuple([x[-1] for x in test])

我还看过:

secondonly = tuple([x for word, x in test]) <---- ** <--- 它是如何工作的?

有人可以向我解释带有 ** 的行是如何给出好的结果的吗?谢谢

最佳答案

test 包含 3 个长度为 2 的元组。for word, x in test(相当于 for (word, x) in test) 将每个元组的第一个元素解包为 word,将第二个元素解包为 x。因此 [x for (word, x) in test] 每隔一个元素 (x) 创建一个列表。

关于元组提取的python元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22441101/

相关文章:

python - 嵌套字典理解python

python - Pandas - 比较 2 列并根据优先级选择值

python - 将 "Quoted-printable"编码改为 "utf-8"

python - XLRD 似乎没有在文件中找到我的变量

python - 词典列表,如何获取 : intersection based on one value and symmetric difference based on another value

Python 列表理解技巧

python - 无法在 FOR 循环 Python 中解压元组对象

c++ - 从 C/C++ 库中解压缩可执行文件

Scala:将元组解包为参数列表的一部分

python - 在列表中的对字符串之前用数字替换 Pandas 中的字符串