简体   繁体   English

将列表转换为2元组列表

[英]Convert list into a list of 2-tuples

I have a list: 我有一个清单:

list = [1, 2, 3]

I want to get this list and add a tuple so this list becomes like this 我想得到这个列表并添加一个元组,所以这个列表就像这样

T_list = [(1,x), (2, x), (3,x)]

How do I do it? 我该怎么做?

Use a simple list comprehension to do this: 使用简单的列表理解来执行此操作:

>>> your_list = [1, 2, 3]
>>> x = 100
>>> your_list_with_tuples = [(k, x) for k in your_list]
>>> your_list_with_tuples

Output 产量

[(1, 100), (2, 100), (3, 100)]

Also, don't name your variables list , dict , etc, because they shadow the builtin types/functions. 另外,不要将变量listdict等命名,因为它们会影响内置类型/函数。

A list comprehension would do the trick: 列表理解可以解决这个问题:

t_list = [(y,x) for y in original_list]

Also, the commenter is right. 此外,评论者是对的。 Don't name your lists list . 不要列出您的列表list It's a built in function. 它是内置功能。 Using it for something else could cause problems down the line. 将它用于其他事情可能会导致问题。

Here's my attempt, although I'm not an expert. 这是我的尝试,虽然我不是专家。

lis = [1,2,3]
tup = (4, 5, 6)

new_tup = tuple(lis)
new_lis = []
for i in range(0,3):
    data = (new_tup[i],tup[i])
    new_lis.append(data)
print(new_lis)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM