Converting each element of a list to tuple

萝らか妹 提交于 2019-12-07 14:42:36

问题


I to convert each element of list to tuple like following :

l = ['abc','xyz','test']

convert to tuple list:

newl = [('abc',),('xyz',),('test',)]

Actually I have dict with keys like this so for searching purpose I need to have these.


回答1:


You can use a list comprehension:

>>> l = ['abc','xyz','test']
>>> [(x,) for x in l]
[('abc',), ('xyz',), ('test',)]
>>>

Or, if you are on Python 2.x, you could just use zip:

>>> # Python 2.x interpreter
>>> l = ['abc','xyz','test']
>>> zip(l)
[('abc',), ('xyz',), ('test',)]
>>>

However, the previous solution will not work in Python 3.x because zip now returns a zip object. Instead, you would need to explicitly make the results a list by placing them in list:

>>> # Python 3.x interpreter
>>> l = ['abc','xyz','test']
>>> zip(l)
<zip object at 0x020A3170>
>>> list(zip(l))
[('abc',), ('xyz',), ('test',)]
>>>

I personally prefer the list comprehension over this last solution though.




回答2:


Just do this:

newl = [(i, ) for i in l]


来源:https://stackoverflow.com/questions/22256366/converting-each-element-of-a-list-to-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!