📜  Python - 使用 for 循环创建元组列表

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

Python - 使用 for 循环创建元组列表

在本文中,我们将讨论如何在Python使用 for 循环创建元组列表。

假设我们有一个列表,我们想要从该列表中创建一个元组列表,其中元组的每个元素都将包含列表元素及其相应的索引。

方法 1:将 For 循环与 append() 方法一起使用

在这里,我们将使用 for 循环和 append() 方法。我们将遍历列表的元素,并使用 append()方法向结果列表添加一个元组

例子:

Python3
L = [5, 4, 2, 5, 6, 1]
res = []
  
for i in range(len(L)):
    res.append((L[i], i))
      
print("List of Tuples")
print(res)


Python3
L = [5, 4, 2, 5, 6, 1]
res = []
  
for index, element in enumerate(L):
    res.append((element, index))
      
print("List of Tuples")
print(res)


输出

List of Tuples
[(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]

方法 2:在 enumerate() 方法中使用 For 循环

Enumerate() 方法向可迭代对象添加一个计数器并以枚举对象的形式返回它。所以我们可以使用这个函数来创建所需的元组列表。

例子:

蟒蛇3

L = [5, 4, 2, 5, 6, 1]
res = []
  
for index, element in enumerate(L):
    res.append((element, index))
      
print("List of Tuples")
print(res)
输出
List of Tuples
[(5, 0), (4, 1), (2, 2), (5, 3), (6, 4), (1, 5)]