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?
>>> ', '.join(i + '=' + j for i,j in zip(a,b))
'a1=b1, a2=b2, a3=b3'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With