Skip to content

26.5 两个等长list之间的merge(paste)操作

https://scz.617.cn/python/201112271246.txt

Q:

Unix有个paste命令,可以合并两个行数相等的文本文件。现有两个list:

x=['a','b','c'] y=['d','e','f']

我想得到新list:

['ad','be','cf']

但我不想用for循环:

x = ['a','b','c'] y = ['d','e','f'] n = len( x ) ret = [] for i in range( n ) : ret.append( x[i] + y[i] )

print ret

A: scz@nsfocus 2011-12-27 12:46

可以用高序函数:

map((lambda x,y:x+y),x,y)

A: lotrpy@weibo 2011-12-27 19:07

[''.join(z) for z in zip(x,y)]

效率比map()低:

python -m timeit -s "x=['a','b','c'];y=['d','e','f']" "map((lambda x,y:x+y),x,y)"

100000 loops, best of 3: 2.1 usec per loop

python -m timeit -s "x=['a','b','c'];y=['d','e','f']" "[''.join(z) for z in zip(x,y)]"

100000 loops, best of 3: 2.24 usec per loop

A: hume 2011-12-28 18:41

[v+y[i] for i,v in enumerate(x)]

这个效率比前面的都高:

python -m timeit -s "x=['a','b','c'];y=['d','e','f']" "[v+y[i] for i,v in enumerate(x)]"

1000000 loops, best of 3: 1.55 usec per loop

A: lzx@nsfocus 2012-01-05 18:30

[x[i]+y[i] for i in range(len(x))]

这个和用enumerate效率差不多,不过这个似乎更容易想到一些。

python -m timeit -s "x=['a','b','c'];y=['d','e','f']" "[x[i]+y[i] for i in range(len(x))]"

1000000 loops, best of 3: 1.58 usec per loop

A: zyh@nsfocus 2012-01-06 18:44

[i+j for i,j in zip(x,y)]

python -m timeit -s "x=['a','b','c'];y=['d','e','f']" "[i+j for i,j in zip(x,y)]"

1000000 loops, best of 3: 1.94 usec per loop

A: 请叫我李牛牛@weibo 2012-01-06 22:37

python -m timeit -s "x=['a','b','c'];y=['d','e','f'];L=len(x)" "[x[i]+y[i] for i in xrange(L)]"

1000000 loops, best of 3: 1.22 usec per loop

python -m timeit -s "x=['a','b','c'];y=['d','e','f']" "[x[i]+y[i] for i in xrange(len(x))]"

1000000 loops, best of 3: 1.4 usec per loop

python -m timeit -s "x=['a','b','c'];y=['d','e','f'];L=len(x)" "[x[i]+y[i] for i in range(L)]"

1000000 loops, best of 3: 1.46 usec per loop

python -m timeit -s "x=['a','b','c'];y=['d','e','f']" "[x[i]+y[i] for i in range(len(x))]"

1000000 loops, best of 3: 1.58 usec per loop

可以看出,用xrange()代替range(),把len()移出for循环,效率提升明显,其中第 一条效率提升更多。

A: hw@nsfocus 2012-01-09 15:10

python -m timeit -s "x=['a','b','c'];y=['d','e','f'];from itertools import izip" "[i+j for i,j in izip(x,y)]"

1000000 loops, best of 3: 1.43 usec per loop

当x、y是小list时,用izip()没有xrange()快,当x、y是大list时,izip()效率优势 明显。