如何将列表转换为元组列表? [英] How to convert a list to a list of tuples?

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

问题描述

我是Python的新手,需要将列表转换为字典.我知道我们可以将元组列表转换为字典.

I am newbie to Python and need to convert a list to dictionary. I know that we can convert a list of tuples to a dictionary.

这是输入列表:

L = [1,term1, 3, term2, x, term3,... z, termN]

,我想将此列表转换为元组列表(或直接转换为字典),如下所示:

and I want to convert this list to a list of tuples (or directly to a dictionary) like this:

[(1, term1), (3, term2), (x, term3), ...(z, termN)]

我们如何在Python中轻松地做到这一点?

How can we do that easily in Python?

推荐答案

>>> L = [1, "term1", 3, "term2", 4, "term3", 5, "termN"]
# Create an iterator
>>> it = iter(L)
# zip the iterator with itself
>>> zip(it, it)
[(1, 'term1'), (3, 'term2'), (4, 'term3'), (5, 'termN')]

您想一次将三个项目分组吗?

You want to group three items at a time?

>>> zip(it, it, it)

您想一次将N个项目分组吗?

You want to group N items at a time?

# Create N copies of the same iterator
it = [iter(L)] * N
# Unpack the copies of the iterator, and pass them as parameters to zip
>>> zip(*it)

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

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