本文为博主原创文章,未经博主允许不得转载。
在Python的数据类型中没有数组,但是有比数组更强大的工具——列表(Sequences),本文将介绍Sequences中list的用法。
创建list
>>> list1=[1,2,3]
>>> list2=[]
>>> list3=[1,"string",3.14,[1,2,3]]
从代码中可以看到我们可以直接像C语言数组一样初始化list,而且list最初也可以为空,此外list可以杂糅多种数据类型如list3所示,以上是基本的创建方式。
高级创建介绍:
list支持方法list()来创建,其中括号内可以接受sequence和tulpe作为参数,并把它们转化为list,例如:
>>> list4=list([1,2])
>>> list4
[1, 2]
此外list的创建支持一种叫做“列表推导(List Comprehension)”的创建方式,它的语法表达形式如下:
theList = [expression(iter) for iter in oldList if filter(iter)]
下面给出简单的例子:
>>> list5=[a*a for a in range(1,5)]
>>> list5
[1, 4, 9, 16]
再来一个不同的例子:
>>> list6=[m+n for m in range(1,3) for n in range(3,5)]
>>> list6
[4, 5, 5, 6]
可以看到m中的元素把n中的元素都加了一遍,这点得注意。
接下来看复杂的创建例子:
>>> list7=[x+y for x in"abc" for y in "def" if x!='c' and y!='f']
>>> list7
['ad', 'ae', 'bd', 'be']
这里面增加了条件:x不能为c,y不能为f。
其实还有很多有趣的例子:
>>> listofcolor=["red","blue","yellow"]
>>> secondletters=[color[1] for color in listofcolor]
>>> secondletters
['e', 'l', 'e']
>>> months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']
>>> evenmonths=[iter for index,iter in enumerate(months) if(index%2==1)]
>>> evenmonths
['feb', 'apr', 'jun', 'aug', 'oct', 'dec']
上文中enumerate()是Python内置函数,用于枚举。
其它创建方式:
快速创建许多相同元数的列表:
>>> list8=[1]*3
>>> list8
[1, 1, 1]
二维数组:
>>> list9=[[1]*3]*3
>>> list9
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> list9[1][2]=0
>>> list9
[[1, 1, 0], [1, 1, 0], [1, 1, 0]]
从上面可以看到,修改数据时,所以行的数据都被修改了,那么有没有办法避免这个问题呢?
这时就要用到List Comprehension来创建list
>>> list10=[[1]*3 for i in range(3)]
>>> list10
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> list10[1][2]=0
>>> list10
[[1, 1, 1], [1, 1, 0], [1, 1, 1]]