Lets say I have two lists of same length:
a = ['a1', 'a2', 'a3']
b = ['b1', 'b2', 'b3']
and I want to produce the following string:
c = 'a1=b1, a2=b2, a3=b3'
What is the best way to achieve this?
I have following implementations:
import timeit
a = [str(f) for f in range(500)]
b = [str(f) for f in range(500)]
def func1():
return ', '.join([aa+'='+bb for aa in a for bb in b if a.index(aa) == b.index(bb)])
def func2():
list = []
for i in range(len(a)):
list.append('%s=%s' % (a[i], b[i]))
return ', '.join(list)
t = timeit.Timer(setup='from __main__ import func1', stmt='func1()')
print 'func1 = ' + t.timeit(10)
t = timeit.Timer(setup='from __main__ import func2', stmt='func2()')
print 'func2 = ' + t.timeit(10)
and the output is:
func1 = 32.4704790115
func2 = 0.00529003143311
Do you have some trade-off?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…