An Array of Sequences
Posted neozheng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了An Array of Sequences相关的知识,希望对你有一定的参考价值。
1. Listcomps (List comprehensions) do everything the map and filter functions do. (map 函数和 filter函数能做的,列表生成式都可以做)
列表生成式和 map, filter 函数运行时间的比较示例:
import timeit TIMES = 10000 SETUP = """ symbols = ‘$¢£¥€¤‘ def non_ascii(c): return c > 127 """ timeit.timeit() def clock(label, cmd): res = timeit.repeat(cmd, setup=SETUP, number=TIMES) print(label, *(‘{:.3f}‘.format(x) for x in res)) clock(‘listcomp :‘, ‘[ord(s) for s in symbols if ord(s) > 127]‘) clock(‘listcomp + func :‘, ‘[ord(s) for s in symbols if non_ascii(ord(s))]‘) clock(‘filter + lambda :‘, ‘list(filter(lambda c: c > 127, map(ord, symbols)))‘) clock(‘filter + func :‘, ‘list(filter(non_ascii, map(ord, symbols)))‘) # 测试一段代码的运行时间,可以用 timeit 模块 """ timeit 模块中主要函数有两个: 1. timeit(stmt=‘pass‘, setup=‘pass‘, timer=<defaulttimer>, number=1000000) 返回: 返回执行stmt这段代码number遍所用的时间,单位为秒,float型 参数: stmt:要执行的那段代码 setup:执行代码的准备工作,不计入时间,一般是import之类的 timer:这个在win32下是time.clock(),linux下是time.time(),默认的,不用管 number:要执行stmt多少遍 2. repeat(stmt=‘pass‘, setup=‘pass‘, timer=<defaulttimer>, repeat=3, number=1000000) 这个函数比timeit函数多了一个repeat参数而已,表示重复执行timeit这个过程多少遍,返回一个列表,表示执行每遍的时间;repeat默认为3 """
timeit 参考链接:https://www.cnblogs.com/itcomputer/articles/4578769.html
2. Tuple
In [44]: traveler_ids = [(‘USA‘,‘31195855‘), (‘BRA‘,‘CE342567‘), (‘ESP‘, ‘XDA205856‘)] In [45]: for passport in sorted(traveler_ids): ...: print(‘%s/%s‘ % passport) ...: BRA/CE342567 ESP/XDA205856 USA/31195855 # The % formatting operator understands tuples and treats each item as a separate field. # Tuple Unpacking In [46]: t = (20, 8) In [47]: divmod(*t) Out[47]: (2, 4) In [48]: quotient,remainder = divmod(*t) In [49]: quotient, remainder Out[49]: (2, 4) # Using * to grab excess items In [50]: a, b, *rest = range(5) In [51]: a, b, rest Out[51]: (0, 1, [2, 3, 4]) In [52]: a, b, *rest = range(2) In [53]: a, b, rest Out[53]: (0, 1, []) In [54]: a, *body, c, d = range(5) In [55]: a, body, c, d Out[55]: (0, [1, 2], 3, 4) # In the context of parallel assignment, the * prefix can be applied to exactly one variable, but it can appear in any position # Nested Tuple Unpacking metro_areas = [ (‘Tokyo‘, ‘JP‘, 36.933, (35.689722, 139.691667)), (‘Mexico City‘, ‘MX‘, 20.142, (19.433333, -99.133333)), (‘New York-Newark‘, ‘US‘, 20.104, (40.808611, -74.020386)), ] print(‘{:15} | {:^9} | {:^9}‘.format(‘‘, ‘lat.‘, ‘long.‘)) fmt = ‘{:15} | {:9.4f} | {:9.4f}‘ # By assigning the last field to a tuple, we unpack the coordinates. for name, cc, pop, (latitude, longitude) in metro_areas: if longitude <= 0: print(fmt.format(name, latitude, longitude)) # Output: """ | lat. | long. Mexico City | 19.4333 | -99.1333 New York-Newark | 40.8086 | -74.0204 """
字符串格式化参考链接: https://www.cnblogs.com/songdanlee/p/11105807.html
end
以上是关于An Array of Sequences的主要内容,如果未能解决你的问题,请参考以下文章