深度阅读

How to create a list of tuples in Python

作者
作者
2023年08月22日
更新时间
14.81 分钟
阅读时间
0
阅读量

To create a list of tuples in Python, you can use a combination of the zip() function, list comprehension, or the tuple() function. Here are some examples:

# Using zip() and a for loop:
my_list = ['apple', 'banana', 'cherry']
my_tuple = (1, 2, 3)
my_list_of_tuples = []
for i in range(len(my_list)):
    my_list_of_tuples.append((my_list[i], my_tuple[i]))
print(my_list_of_tuples)    # Output: [('apple', 1), ('banana', 2), ('cherry', 3)]

# Using zip() and list comprehension:
my_list = ['apple', 'banana', 'cherry']
my_tuple = (1, 2, 3)
my_list_of_tuples = [(i, j) for i, j in zip(my_list, my_tuple)]
print(my_list_of_tuples)    # Output: [('apple', 1), ('banana', 2), ('cherry', 3)]

# Using tuple() and list comprehension:
my_list = ['apple', 'banana', 'cherry']
my_tuple = (1, 2, 3)
my_list_of_tuples = [tuple(i) for i in zip(my_list, my_tuple)]
print(my_list_of_tuples)    # Output: [('apple', 1), ('banana', 2), ('cherry', 3)]

In the first example, we use a for loop to iterate through both lists, and use the append() method to add each tuple to a new list called my_list_of_tuples.

In the second example, we use list comprehension and the zip() function to create a list of tuples.

In the third example, we use list comprehension and the tuple() function to convert the zip output to tuples.

These examples demonstrate three different ways to achieve the same result, so you can choose the method that works best for your specific use case.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。