简体   繁体   中英

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",)] . 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(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()

>>> 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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