流畅的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])

猜你喜欢

转载自www.cnblogs.com/lw-monster/p/11966441.html