Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

smartest way to join two lists into a formatted string

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?

like image 304
Jib Avatar asked Sep 01 '11 22:09

Jib


1 Answers

>>> ', '.join(i + '=' + j for i,j in zip(a,b))
'a1=b1, a2=b2, a3=b3'
like image 100
JBernardo Avatar answered Oct 23 '22 09:10

JBernardo