RSS

Category Archives: Python

timeit测试Python中tuple格式化字符串的各种方法

偶尔格式化字符串时会加入tuple,我一直弱弱地这么做:

tup = (1, 2)
'tup: (%d, %d)' % (tup[0], tup[1])

或者这么做

tup = (1, 2)
'tup: %s' % str(tup)

今天搜索到 http://stackoverflow.com/questions/1455602/printing-tuple-with-string-formatting-in-python

提到了下列方法:

tup = (1, 2)
'tup: %s' % (tup,)
'tup: %s' % repr(tup)
'tup: %s' % str(tup)
'tup: {0}'.format(tup)

测了一下文中提到的和我使用的土鳖方法,python 2.7.5结果如下:

Python 2.7.5 (default, Mar  9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import timeit
>>> timeit.timeit("'%s' %((1,2),)", number=10000000)
6.564547061920166
>>> timeit.timeit("'%s' % repr((1,2))", number=10000000)
7.188735008239746
>>> timeit.timeit("'%s' % str((1,2))", number=10000000)
8.625754117965698
>>> timeit.timeit("'(%d, %d)' % (1,2)", number=10000000)
10.319281101226807
>>> timeit.timeit("'(%d, %d)' % ((1,2)[0], (1,2)[1])", number=10000000)
11.005209922790527
>>> timeit.timeit("'{0}'.format((1,2))", number=10000000)
13.548444986343384

不过在我目前使用的python 3.4.1上成功翻盘:),结果如下:

Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> import timeit
>>> timeit.timeit("'%s' %((1,2),)", number=10000000)
0.2406598930247128
>>> timeit.timeit("'%s' % repr((1,2))", number=10000000)
6.812374057015404
>>> timeit.timeit("'%s' % str((1,2))", number=10000000)
8.0442612930201
>>> timeit.timeit("'(%d, %d)' % (1,2)", number=10000000)
0.2473735569510609
>>> timeit.timeit("'(%d, %d)' % ((1,2)[0], (1,2)[1])", number=10000000)
0.23919461597688496
>>> timeit.timeit("'{0}'.format((1,2))", number=10000000)
12.90034785703756

所以下面的方法在python 2.7.5和python 3.4.1上都是最快的(或之一)

tup = (1, 2)
'tup: %s' % (tup,)

值得一提的是文中一位老兄说的

Note that the % syntax is obsolete. Use str.format, which is simpler and more readable:
t = 1,2,3
print ‘This is a tuple {0}’.format(t)

真的是很慢啊。


 
添加留言

Posted by on 八月 12, 2014 in Python

 

Tags: , , ,

Python中初始化多元数组

在python中有多种方式初始化多元数组,以二元数组为例:

我们可以写成最直观的形式:

two_d_list = []
nested_list = []
for i in range(num_1):
    for j in range(num_2):
        nested_list.append(foo)
    two_d_list.append(nested_list)
    nested_list = []

或者是看起来pythonic一点的形式:

two_d_list = [[foo for i in range(num_2)] for j in range(num_1)]

又或者是效率更高的形式:

two_d_list = [x[:] for x in [[foo]*num_2]*num_1]

如果是数值处理,引入numpy也是一个很好的选择:

import numpy
two_d_list_1 = numpy.zeros((num_1, num_2))
two_d_list_2 = numpy.empty((num_1, num_2))
two_d_list_2.fill(foo)
 
添加留言

Posted by on 八月 6, 2014 in Python

 

Tags: , , ,