简体   繁体   中英

Python: How to convert a list to a list of tuples?

for example, i have a list below,

['Visa', 'Rogers', 'Visa']

if i want to convert it to a list of tuples, like

[('Visa',), ('Rogers',), ('Visa',)]

How can I convert it?

>>> [(x,) for x in ['Visa', 'Rogers', 'Visa']]
[('Visa',), ('Rogers',), ('Visa',)]

simple list comprehension will do the trick. make sure to have the , to specify single item tuples (you will just have the original strings instead)

Doing some kind of operation for each element can be done with map() or list comprehensions :

a = ['Visa', 'Rogers', 'Visa']

b = [(v,) for v in a]
c = map(lambda v: (v,), a)

print(b) # [('Visa',), ('Rogers',), ('Visa',)]
print(c) # [('Visa',), ('Rogers',), ('Visa',)]

Please keep in mind that 1-element-tuples are represented as (value,) to distinguish them from just a grouping/regular parantheses

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