流畅的python--序列构成的数组
''' 容器序列 list tuple collections.deque 能存放不同类型的数据,容器序列存放的是他们所包含的任意类型的对象的引用,当对容器序列进行更改时,外部数据也会更改 扁平序列 str bytes bytearray memoryview array.array 这些序列只能容纳一种类型 可变序列 list bytearray array.array collections.deque memoryview 不可变序列 tuple str bytes ''' #常规写法 symbols = "ABCDE" codes = [] for symbol in symbols: codes.append(ord(symbol)) print(codes) # >> [65, 66, 67, 68, 69] #列表推导 symbols2 = "ABCDE" #symbol = "EFGH" codes = [ord(symbol) for symbol in symbols] #print(symbol) #2.x 版本 结果是 H ,变量泄露, 3.x不会产生泄露 print(codes) # >> [65, 66, 67, 68, 69] symbols3 = "ABCDEF" beyond_ascii = [ord(s) for s in symbols3 if ord(s)>67] print(beyond_ascii) # >> [68, 69, 70]
''' sysmbols3.where(c=>c>67).tolist() 在symbols3的元素中 十六进制大于67的tolist,不大于67的不tolist ''' beyond_ascii2 = list(filter(lambda c: c>67, map(ord, symbols3))) print(beyond_ascii2) # >> [68, 69, 70] #笛卡尔积 colors = ['black', 'white'] sizes = ['S', 'W', 'L'] males = ['male', 'female'] tshirts = [(color, size) for color in colors for size in sizes] print(tshirts) # >> [('black', 'S'), ('black', 'W'), ('black', 'L'), ('white', 'S'), ('white', 'W'), ('white', 'L')] for color in colors: for size in sizes: print((color, size)) ''' >> 输出 ('black', 'S') ('black', 'W') ('black', 'L') ('white', 'S') ('white', 'W') ('white', 'L') ''' tshirts2 = [(size, color) for color in colors for size in sizes] print(tshirts2) # >> [('S', 'black'), ('W', 'black'), ('L', 'black'), ('S', 'white'), ('W', 'white'), ('L', 'white')] tshirts3 = [(male, size, color) for male in males for color in colors for size in sizes] print(tshirts3) # >> [('male', 'S', 'black'), ('male', 'W', 'black'), ('male', 'L', 'black'), ('male', 'S', 'white'), ('male', 'W', 'white'), ('male', 'L', 'white'), ('female', 'S', 'black'), ('female', 'W', 'black'), ('female', 'L', 'black'), ('female', 'S', 'white'), ('female', 'W', 'white'), ('female', 'L', 'white')] #生成表达式 symbols4 = "ABCDEFG" codes4 = tuple(ord(symbol) for symbol in symbols4) print(codes4) # >> (65, 66, 67, 68, 69, 70, 71) import array codes5 = array.array('I', (ord(symbol) for symbol in symbols4)) print(codes5) # >> array('I', [65, 66, 67, 68, 69, 70, 71])
lax_coordinates = (33.9425, -118.400056) #元组 print(lax_coordinates) # >> (33.9425, -118.400056) print("%s/%s" % lax_coordinates) # >> 33.9425/-118.400056 latitude, longitude = lax_coordinates #元组的拆包 print(latitude) # >> 33.9425 print(longitude) # >> -118.400056 city, year, pop, chg, area = ('Tokyo', 2003, 32450, 0.66, 8014) traveler_ids = [('USA', '31195855'),('BRA', 'CE342567'),('ESP', 'XDA205856')] for passport in sorted(traveler_ids): print('%s/%s'%passport) ''' >> BRA/CE342567 ESP/XDA205856 USA/31195855 ''' for country, _ in traveler_ids: # 只打印出country print(country) ''' >> USA BRA ESP ''' print(divmod(20, 8)) # >> (2, 4) t = (20, 8) quotient, remainder = divmod(*t) print(quotient) # >> 2 print(remainder) # >> 4 import os _, filename = os.path.split('/home/luciano/.ssh/idrsa.pub') print(filename) # >> idrsa.pub a,b,*rest = range(5) # 用*来处理剩下的元素,在平行赋值中, * 前缀只能用在一个变量名前面, 但是这个变量可以出现在赋值表达式的任意位置 print('%r/%r/%r' %(a,b,rest)) # >> 0/1/[2, 3, 4] a1, b1, *rest1 = range(2) # 0 1 print('%r/%r/%r' %(a1,b1,rest1)) # >> 0/1/[] a2, *rest2, b2 =range(5) print('%r/%r/%r' %(a2, rest2, b2)) # >> 0/[1, 2, 3]/4 #嵌套元组 metro_areas = [ ('Tokyo', 'JP', 36.933, (35.689722, 139.691667)), ('Delhi NCP', 'IN', 21.935, (28.613889, 77.208889)), ('Mexico City', 'MX', 20.142, (19.433333, -99.133333)) ] print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.')) fmt = '{:15} | {:9.4f} | {:9.4f}' #嵌套式元组的拆包 for name, cc, pop, (latitude, longtitude) in metro_areas: if longitude <- 0: print(fmt.format(name, latitude, longitude)) ''' >> | lat. | long. Tokyo | 35.6897 | -118.4001 Delhi NCP | 28.6139 | -118.4001 Mexico City | 19.4333 | -118.4001 ''' #具名元组 from collections import namedtuple City = namedtuple('City', 'name country population coordinates') tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667)) print(tokyo) # >> City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722, 139.691667)) print(tokyo.population) # >> 36.933 print(tokyo[1]) # >> JP print(City._fields) # >> ('name', 'country', 'population', 'coordinates') #具名元组的属性 LatLong = namedtuple('LatLong', 'lat long') delhi_data = ('Delhi NCP', 'IN', 21.935, (28.613889, 77.208889)) delhi = City._make(delhi_data) #用 _make() 通过接受一个可迭代对象来生成这个类的一个实例, 它的作用跟 City(*delhi_data) 是一样的
print(delhi)
# >> City(name='Delhi NCP', country='IN', population=21.935, coordinates=(28.613889, 77.208889))
print(delhi._asdict()) #_asdict() 把具名元组以 collections.OrderedDict 的形式返回, 我们可以利用它来把元组里的信息友好地呈现出来
# >> OrderedDict([('name', 'Delhi NCP'), ('country', 'IN'), ('population', 21.935), ('coordinates', (28.613889, 77.208889))])
for key, value in delhi._asdict().items(): print(key + ':', value) ''' >> name: Delhi NCP country: IN population: 21.935 coordinates: (28.613889, 77.208889) '''