假设我有一个数字15
和数字列表:
[5, 6, 7, 8]
现在我想制作像
这样的元组列表[(15,6), (15,5), (15,7), (15,8)]
如何快速完成?
答案 0 :(得分:2)
list_of_nums = [5, 6, 7, 8]
result = [(15, num) for num in list_of_nums]
每当你有一个进程根据另一个序列的输出产生一个列表时,通常列表理解就可以完成这项工作。
演示:
>>> list_of_nums = [5, 6, 7, 8]
>>> [(15, num) for num in list_of_nums]
[(15, 5), (15, 6), (15, 7), (15, 8)]
答案 1 :(得分:0)
您也可以尝试zip
功能
result = zip([15]*len(list_of_nums),list_of_nums)
print(result)
[(15, 5), (15, 6), (15, 7), (15, 8)]