将列表的每个元素转换为元组 [英] Converting each element of a list to tuple

查看:1239
本文介绍了将列表的每个元素转换为元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将列表的每个元素转换为元组,如下所示:

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

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

转换为元组列表:

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

实际上,我用这样的键来字典,因此出于搜索目的,我需要这些键.

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

推荐答案

您可以使用列表理解:

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


或者,如果您使用的是Python 2.x,则可以使用 zip :


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',)]
>>>


但是,以前的解决方案在Python 3.x中不起作用,因为zip现在返回一个zip对象.相反,您需要通过将结果放在 :


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.

这篇关于将列表的每个元素转换为元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆