简体   繁体   English

Python从两个列表和一个常量中创建元组列表

[英]Python make list of tuples from two lists and a constant

I would like to make a list of tuples using two lists and a constant, as follows, I'd like to generate ob in the fast way possible. 我想使用两个列表和一个常量来创建元组列表,如下所示,我想以尽可能快的方式生成ob。 I need to make about a hundred thousand of these, so time matters... 我需要制作大约十万个,所以时间很重要......

On average the size A and B have a length of about 1000 平均而言,尺寸A和B的长度约为1000

constant = 3
A = [1,2,3]
B = [0.1,0.2,0.3]
ob = [(3,1,0.1),(3,2,0.2),(3,3,0.3)]

I know zip(A,B) can create a list of tuples but I need the constant at the beginning. 我知道zip(A,B)可以创建一个元组列表,但我需要一开始的常量。 Here is the code I am using at them moment, I was wondering if there is a faster way to do this 这是我在他们使用的代码时刻,我想知道是否有更快的方法来做到这一点

ob = []
for i in xrange(len(A)):
    a = A[i]
    b = B[i]
    ob.append((constant,a,b))

print ob

I suggestion the following solution still based on zip() built-in function , without any needed import directive: 我建议以下解决方案仍然基于zip()内置函数 ,没有任何需要的import指令:

constant = 3
A = [1,2,3]
B = [0.1,0.2,0.3]

ob = list(zip([constant]*len(A), A ,B))

print(ob)  # [(3,1,0.1),(3,2,0.2),(3,3,0.3)]

You could use itertools.repeat : 你可以使用itertools.repeat

from itertools import repeat

ob = list(zip(repeat(constant), A, B))

use itertools.cycle 使用itertools.cycle

import itertools 
ob = list( zip( itertools.cycle([3]) , A , B ) )

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

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