切片器和列表生成器
Posted gost
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了切片器和列表生成器相关的知识,希望对你有一定的参考价值。
使用切片器对list,tuple,或者string进行处理
>>> lis = [1,2,3,4,5,6,7,8,9,10] >>> lis[:5] [1, 2, 3, 4, 5] #取前5个 >>> lis[5:] [6, 7, 8, 9, 10] # 取后5个 >>> lis[::2] [1, 3, 5, 7, 9] #隔两个取一个 >>> lis[:] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #复制
列表生成器
>>> [i for i in range(10)] #生成一个0到9的list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> [i*i for i in range(10)] #参数也可以计算 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> [i*i for i in range(10) if i %2 ==0] #对参数进行条件判断 [0, 4, 16, 36, 64] >>> a = [‘a‘,‘b‘,‘c‘,‘d‘] >>> b=[‘1‘,‘2‘,‘3‘,‘4‘] >>> [i+j for i in a for j in b] [‘a1‘, ‘a2‘, ‘a3‘, ‘a4‘, ‘b1‘, ‘b2‘, ‘b3‘, ‘b4‘, ‘c1‘, ‘c2‘, ‘c3‘, ‘c4‘, ‘d1‘, ‘d2‘, ‘d3‘, ‘d4‘] #二维的排列组合 >>> [(i,j) for i in a for j in b] [(‘a‘, ‘1‘), (‘a‘, ‘2‘), (‘a‘, ‘3‘), (‘a‘, ‘4‘), (‘b‘, ‘1‘), (‘b‘, ‘2‘), (‘b‘, ‘3‘), (‘b‘, ‘4‘), (‘c‘, ‘1‘), (‘c‘, ‘2‘), (‘c‘, ‘3‘), (‘c‘, ‘4‘), (‘d‘, ‘1‘), (‘d‘, ‘2‘), (‘d‘, ‘3‘), (‘d‘, ‘4‘)] #生成tuple >>> [[i,j] for i in a for j in b] [[‘a‘, ‘1‘], [‘a‘, ‘2‘], [‘a‘, ‘3‘], [‘a‘, ‘4‘], [‘b‘, ‘1‘], [‘b‘, ‘2‘], [‘b‘, ‘3‘], [‘b‘, ‘4‘], [‘c‘, ‘1‘], [‘c‘, ‘2‘], [‘c‘, ‘3‘], [‘c‘, ‘4‘], [‘d‘, ‘1‘], [‘d‘, ‘2‘], [‘d‘, ‘3‘], [‘d‘, ‘4‘]] #生成list >>> [i for i in os.listdir()] #获取当前目录中的文件 [‘chromedriver.exe‘, ‘curl.exe‘, ‘DLLs‘, ‘Doc‘, ‘geckodriver.exe‘, ‘include‘, ‘Lib‘, ‘libs‘, ‘LICENSE.txt‘, ‘NEWS.txt‘, ‘python.exe‘, ‘python3.dll‘, ‘python37.dll‘, ‘pythonw.exe‘, ‘Scripts‘, ‘tcl‘, ‘Tools‘, ‘vcruntime140.dll‘] >>> [i if i %2 ==0 else 0 for i in range(10)] #if else 表达式的使用 [0, 0, 2, 0, 4, 0, 6, 0, 8, 0] >>> lis = [‘ ad‘,‘4654 6‘,‘sfaf daf ‘] # 快速去除列表中的字符串中的空格 >>> [i.strip() for i in lis] [‘ad‘, ‘4654 6‘, ‘sfaf daf‘]
以上是关于切片器和列表生成器的主要内容,如果未能解决你的问题,请参考以下文章