简体   繁体   English

迭代元组列表并仅解压第一个元素

[英]Iterate over list of tuples and unpack first elements only

Assume the following list: foo = [(1, 2, 3, 4), (5, 6, 7, 8)]假设有以下列表: foo = [(1, 2, 3, 4), (5, 6, 7, 8)]

Is there a way to iterate over the list and unpack the first two elements of the inner tuple only?有没有办法遍历列表并仅解包内部元组的前两个元素?

This is a usual pattern: {a: b for a, b, _, _ in foo} , but this breaks if foo is modified (program change) and the tuple now contains 5 elements instead of 4 (the the list comprehension would need to be modified accordingly).这是一个通常的模式: {a: b for a, b, _, _ in foo} ,但是如果foo被修改(程序更改)并且元组现在包含 5 个元素而不是 4 个(列表理解需要作相应修改)。 I really like to name the elements instead of calling {f[0]: f[1] for f in foo} , so ideally, there would be some sort of "absorb all not unpacked variable", so one could call {a: b for a, b, absorb_rest in foo} .我真的很喜欢命名元素而不是调用{f[0]: f[1] for f in foo} ,所以理想情况下,会有某种“吸收所有未解压的变量”,所以可以调用{a: b for a, b, absorb_rest in foo} If that's possible, it wouldn't matter how many elements are contained in the tuple (as long as there are at least 2).如果可能的话,元组中包含多少个元素并不重要(只要至少有 2 个)。

You can use extended iterable unpacking , where you extract the first two elements of the tuple, and ignore the rest of the elements.您可以使用扩展的可迭代解包,在其中提取元组的前两个元素,并忽略其余元素。 Note that this only works for python3请注意,这仅适用于python3

{a:b for a, b, *c in foo}                                                                                                                                                             

You can use extended iterable unpacking , keeping in this way the first two values from the iterable and ignoring the rest:您可以使用扩展的可迭代解包,以这种方式保留可迭代的前两个值并忽略其余值:

{a: b for a, b, *_ in foo}
# {1: 2, 5: 6}

Try this :尝试这个 :

dict_ = {a:b for a,b, *_ in foo}

Output :输出

{1: 2, 5: 6}

If foo is changed to [(1, 2, 3, 4,9,0), (5, 6, 7, 8, 11, 16)] by program later, dict_ still remains : {1: 2, 5: 6}如果foo稍后被程序更改为[(1, 2, 3, 4,9,0), (5, 6, 7, 8, 11, 16)]dict_仍然保持: {1: 2, 5: 6}

use lambda使用lambda

foo = [(1, 2, 3, 4), (5, 6, 7, 8)]
output = list(map(lambda x:{x[0]:x[1]}, foo))
print(output)

output输出

[{1: 2}, {5: 6}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM