简体   繁体   English

元组一个数字与数字列表python

[英]tuple one number with list of numbers python

Suppose I have a number 15 and list of numbers: 假设我有一个数字15和数字列表:

[5, 6, 7, 8]

Now I want to make a list of tuples like 现在我想列出一个元组列表

[(15,6), (15,5), (15,7), (15,8)]

How does one do that quickly? 如何快速做到这一点?

Use a list comprehension : 使用列表理解

list_of_nums = [5, 6, 7, 8]
result = [(15, num) for num in list_of_nums]

Whenever you have a process producing a list based on the output of another sequence, usually a list comprehension can do the job. 只要您有一个根据另一个序列的输出生成列表的过程, 通常列表理解就可以完成任务。

Demo: 演示:

>>> list_of_nums = [5, 6, 7, 8]
>>> [(15, num) for num in list_of_nums]
[(15, 5), (15, 6), (15, 7), (15, 8)]

You can also try the zip function 您也可以尝试zip功能

result = zip([15]*len(list_of_nums),list_of_nums)

print(result)
[(15, 5), (15, 6), (15, 7), (15, 8)]

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

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