将列表变成元组python [英] turning a list into a tuple python

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

问题描述

我正在创建一个python程序.

我有一个列表:

[3, 28, 25, 126, 25, 127]

如何将其转换为元组列表,所以该列表变为:

[(3,28),(25,126),(25,127)]

它连接2个元素并组成一个元组.

解决方案

>>> L = [3, 28, 25, 126, 25, 127]
>>> zip(L[0::2], L[1::2])
[(3, 28), (25, 126), (25, 127)]

这将创建两个列表切片,步长为2-一个从索引零开始的步长,第二个从索引1开始的步长.

I am creating a python program.

I have a list:

[3, 28, 25, 126, 25, 127]

How can I turn this into a list of tuples, so the list becomes:

[(3,28),(25,126),(25,127)]

It joins 2 elements and makes a tuple.

解决方案

>>> L = [3, 28, 25, 126, 25, 127]
>>> zip(L[0::2], L[1::2])
[(3, 28), (25, 126), (25, 127)]

This creates two list slices, with a step width of 2 - one starting from index zero, the second starting from index 1. zip then creates the tuples with one element of each iterable.

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

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