假设您有以下元组的元组:
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/