python - 如何在python中将每对列表转换为元组

标签 python list tuples zip

我想将 list = [1,4,2,3,0] 转换为 list_tup = [(1,4),(4,2),(2,3 ),(3,0)]。您可以在下面看到我的代码,但它输出 [(1,4),(2,3)]。我想知道如何调整 zip 中的索引。

list=[1,4,2,3,0]
list_tup = tuple(zip(list[0::2], list[1::2]))

最佳答案

尝试将整个列表与不包含第一个元素的列表一起压缩:

l = [1,4,2,3,0]
print(list(zip(l, l[1:])))

或者使用解压*:

l = [1,4,2,3,0]
print([*zip(l, l[1:])])

它们都输出:

[(1, 4), (4, 2), (2, 3), (3, 0)]

关于python - 如何在python中将每对列表转换为元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65376945/

相关文章:

python - Pandas 数据帧 : convert column to number with default value

html - 将列表内容与页面中心对齐

python - Python 中一个元组中的所有项目

python元组划分

python - beautifulsoup和bs4有什么区别

python - INFO menuinst_win32 :__init__(182): Menu: name: 'Anaconda${PY_VER} ${PLATFORM}'

python - 是否有 "get or default"访问列表的方式?

Python - 如何按照指定的属性顺序对对象数组进行双重排序?

python - 在 Python 中格式化列表

Windows x64 上的 Python x64 位复制文件性能评估/问题