简体   繁体   English

如何将元组列表更改为相同的元组? [Python]

[英]How to change list of tuples to same tuples? [python]

I have list like this:我有这样的清单:

l = [("a"), ("b"), ("c")]

and i need to have:我需要:

l = ("a"), ("b"), ("c")

Someone know some reasonable quick way to do this?有人知道一些合理的快速方法吗?

You said you have a list of tuples.你说你有一个元组列表。 What you've shown isn't actually a list of tuples.您显示的实际上不是元组列表。 It's a list of strings:这是一个字符串列表:

>>> [("a"), ("b"), ("c")]
['a', 'b', 'c']
>>> type(("a"))
<class 'str'>

I think what you meant was l = [("a",), ("b",), ("c",)] .我认为您的意思是l = [("a",), ("b",), ("c",)] That's a list of tuples.这是一个元组列表。

To change your list of tuples into a tuple of tuples, you simply do:要将您的元组列表更改为元组的元组,您只需执行以下操作:

>>> tuple(l)
(('a',), ('b',), ('c',))

EDIT - Note, that the following literal syntax:编辑 - 请注意,以下文字语法:

l = ("a",), ("b",), ("c",)

Is a tuple of tuples.是元组的元组。

You say you want你说你想要

>>> want = ("a"), ("b"), ("c")
>>> want
('a', 'b', 'c')

You say you have你说你有

>>> have = [("a"), ("b"), ("c")]
>>> have
['a', 'b', 'c']

Use tuple() to get what you want from what you have:使用tuple()从你拥有的东西中得到你想要的东西:

>>> tuple(have)
('a', 'b', 'c')
>>> tuple(have) == want
True

If you want to make a list of strings to a tuple of strings simply use tuple()如果您想将字符串列表制作成字符串元组,只需使用 tuple()

>>> l = [("a"), ("b"), ("c")]
>>> l
['a', 'b', 'c']
>>> 
>>> tuple(l)
('a', 'b', 'c')

Is this what you mean?你是这个意思吗?

l = [(1,2),(2,3),(3,4)]
a,b,c = l
# now a = (1,2), b = (2,3), c = (3,4)

Otherwise the other answers should be able to help you.否则其他答案应该能够帮助你。 You might also want to look into the * operator ("unpacks" a list, so eg [*l,(4,5)] == [(1,2),(2,3),(3,4),(4,5)] ) as well.您可能还想查看*运算符(“解包”列表,例如[*l,(4,5)] == [(1,2),(2,3),(3,4),(4,5)] ) 也是如此。

Either way, you might want to improve your phrasing for any other question you intend to post.无论哪种方式,您都可能希望针对您打算发布的任何其他问题改进措辞。 Give concrete examples of what you want, what you tried and what (unintended) effects that had.给出你想要什么、你尝试了什么以及产生了什么(意想不到的)影响的具体例子。

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

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