📜  Python|将列表转换为索引元组列表

📅  最后修改于: 2022-05-13 01:55:49.991000             🧑  作者: Mango

Python|将列表转换为索引元组列表

有时,在使用Python列表时,我们可能会遇到需要将列表转换为元组的问题。这类问题以前也处理过。但有时,我们有它的变体,我们需要将元素的索引与元素一起分配为元组。让我们讨论可以执行此任务的某些方式。

方法 #1:使用list() + enumerate()
上述功能的组合可用于执行此特定任务。在此,我们只是将枚举列表传递给 list(),它返回以第一个元素为索引、第二个为该索引处的列表元素的元组。

# Python3 code to demonstrate working of
# Convert list to indexed tuple
# Using list() + enumerate()
  
# initializing list
test_list = [4, 5, 8, 9, 10]
  
# printing list
print("The original list : " + str(test_list))
  
# Convert list to indexed tuple
# Using list() + enumerate()
res = list(enumerate(test_list))
  
# Printing result
print("List after conversion to tuple list : " + str(res))
输出 :
The original list : [4, 5, 8, 9, 10]
List after conversion to tuple list : [(0, 4), (1, 5), (2, 8), (3, 9), (4, 10)]

方法 #2:使用zip() + range()
上述功能的组合也可用于执行此特定任务。在此,我们仅使用zip()转换为元组和range()的能力来获取元素索引直到长度。这以元组列表的形式将索引与值配对。

# Python3 code to demonstrate working of
# Convert list to indexed tuple
# Using zip() + range()
  
# initializing list
test_list = [4, 5, 8, 9, 10]
  
# printing list
print("The original list : " + str(test_list))
  
# Convert list to indexed tuple
# Using zip() + range()
res = list(zip(range(len(test_list)), test_list))
  
# Printing result
print("List after conversion to tuple list : " + str(res))
输出 :
The original list : [4, 5, 8, 9, 10]
List after conversion to tuple list : [(0, 4), (1, 5), (2, 8), (3, 9), (4, 10)]