提取列表中的元组元素。

huangapple go评论62阅读模式
英文:

Extract tuple elements in list

问题

my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
这个元组,如何将所有值附加到列表和字典中。例如,我希望得到类似于list1 = [1,2,3,a,b,c] 的输出,以此类推,对于字典,我希望得到类似{1:1,2:2,3:3,4:a} 的输出。

对于列表,我尝试使用列表的长度,但是列表元组中的元素长度都不同。因此,我会得到索引超出范围的错误。
我希望将元组列表的所有元素作为单个列表元素。

英文:

my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty'] For this tuple, how can I append all values in list and dictionary. For example, I want output like list1 = [1,2,3,a,b,c] so on and for dictionary I want output like{1:1,2:2,3:3,4:a}.

Thanks in advance.

For list, I tried using length of list but length is different for all tuple elements in list. So I am getting error like index out of range.
I want all elements of list of tuples as single list elements.

答案1

得分: -1

使用嵌套的推导式首先迭代`my_tuples`中的元组然后迭代每个元组中的项将它们放入一个单一的列表或字典中

```python
>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
>>> [i for t in my_tuples for i in t]
[1, 2, 3, 'a', 'b', 'c', 'd', 'e', True, False, 'q', 'w', 'e', 'r', 't', 'y']
>>> {i: v for i, v in enumerate((i for t in my_tuples for i in t), 1)}
{1: 1, 2: 2, 3: 3, 4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: True, 10: False, 11: 'q', 12: 'w', 13: 'e', 14: 'r', 15: 't', 16: 'y'}

由于'qwerty'不是一个元组,它被解包为其各个字符(因为字符串是字符的可迭代对象,就像(1, 2, 3)是整数的可迭代对象一样)。如果这不是你想要的,你可以将它放入你的元组列表中,如(qwerty,),使其成为一个单元素元组,或者你可以在推导式中使用类似(t if isinstance(t, tuple) else (t,))的表达式来完成。


<details>
<summary>英文:</summary>

Use a nested comprehension to iterate first over the tuples in `my_tuples` and then the items in each tuple, putting them into a single list or dictionary:

>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
>>> [i for t in my_tuples for i in t]
[1, 2, 3, 'a', 'b', 'c', 'd', 'e', True, False, 'q', 'w', 'e', 'r', 't', 'y']
>>> {i: v for i, v in enumerate((i for t in my_tuples for i in t), 1)}
{1: 1, 2: 2, 3: 3, 4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: True, 10: False, 11: 'q', 12: 'w', 13: 'e', 14: 'r', 15: 't', 16: 'y'}

Since `&#39;qwerty&#39;` isn&#39;t a tuple, it&#39;s unpacked into its individual characters (since a string is an iterable of characters, the same way that `(1, 2, 3)` is an iterable of ints).  If that wasn&#39;t what you were looking for, you could put it in your list of tuples as `(qwerty,)` to make it a one-element tuple, or you could do it inside the comprehension with an expression like `(t if isinstance(t, tuple) else (t,))`.


</details>



huangapple
  • 本文由 发表于 2023年3月7日 13:22:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75658297.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定