Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This implementation is, on my system, faster than either of your two functions and still more compact.

c = ', '.join('%s=%s' % t for t in zip(a, b))

Thanks to @JBernardo for the suggested improvement.

In more recent syntax, str.format is more appropriate:

c = ', '.join('{}={}'.format(*t) for t in zip(a, b))

This produces the largely the same output, though it can accept any object with a __str__ method, so two lists of integers could still work here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...