将两个列表加入格式化字符串的最聪明方法
问题描述
假设我有两个相同长度的列表:
Lets say I have two lists of same length:
a = ['a1', 'a2', 'a3']
b = ['b1', 'b2', 'b3']
我想生成以下字符串:
c = 'a1=b1, a2=b2, a3=b3'
实现这一目标的最佳方法是什么?
What is the best way to achieve this?
我有以下实现:
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)
输出是:
func1 = 32.4704790115
func2 = 0.00529003143311
你有一些权衡吗?
解决方案
a = ['a1', 'a2', 'a3']
b = ['b1', 'b2', 'b3']
pat = '%s=%%s, %s=%%s, %s=%%s'
print pat % tuple(a) % tuple(b)
给出 a1=b1, a2=b2, a3=b3
.
然后:
from timeit import Timer
from itertools import izip
n = 300
a = [str(f) for f in range(n)]
b = [str(f) for f in range(n)]
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)
def func3():
return ', '.join('%s=%s' % t for t in zip(a, b))
def func4():
return ', '.join('%s=%s' % t for t in izip(a, b))
def func5():
pat = n * '%s=%%s, '
return pat % tuple(a) % tuple(b)
d = dict(zip((1,2,3,4,5),('heavy','append','zip','izip','% formatting')))
for i in xrange(1,6):
t = Timer(setup='from __main__ import func%d'%i, stmt='func%d()'%i)
print 'func%d = %s %s' % (i,t.timeit(10),d[i])
结果
func1 = 16.2272833558 heavy
func2 = 0.00410247671143 append
func3 = 0.00349569568199 zip
func4 = 0.00301686387516 izip
func5 = 0.00157338432678 % formatting
相关文章