python
spyder
python中的列表list相当于一个数字,但这个数组的大小是可以改变的,其中的元素的类型也可以不同。举个例子:xs = [3, 1, 2] # Create a listprint(xs, xs[0]) # Prints '[3, 1, 2] 2'print(xs[-1]) # Negative indices count from the end of the list; prints '2'xs[2] = 'foo' # Lists can contain elements of different typesprint(xs) # Prints '[3, 1, 'foo']'xs.append('bar') # Add a new element to the end of the listprint(xs) # Prints '[3, 1, 'foo', 'bar']'x = xs.pop() # Remove and return the last element of the listprint(x, xs) # Prints 'bar [3, 1, 'foo']'
输出的结果如下:[3, 1, 2] 32[3, 1, 'foo'][3, 1, 'foo', 'bar']bar [3, 1, 'foo']
python 提供一简洁的语法来获取来列表的子列表(sublists)。使用的方法是类似于matlab的语法。例子:nums = list(range(5)) # range is a built-in function that creates a list of integersprint(nums) # Prints '[0, 1, 2, 3, 4]'print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints '[2, 3]'print(nums[2:]) # Get a slice from index 2 to the end; prints '[2, 3, 4]'print(nums[:2]) # Get a slice from the start to index 2 (exclusive); prints '[0, 1]'print(nums[:]) # Get a slice of the whole list; prints '[0, 1, 2, 3, 4]'print(nums[:-1]) # Slice indices can be negative; prints '[0, 1, 2, 3]'nums[2:4] = [8, 9] # Assign a new sublist to a sliceprint(nums) # Prints '[0, 1, 8, 9, 4]'
输出结果如下:[0, 1, 2, 3, 4][2, 3][2, 3, 4][0, 1][0, 1, 2, 3, 4][0, 1, 2, 3][0, 1, 8, 9, 4]
循环:python中使用如下方式扫描一遍列表中的所有元素如下:animals = ['cat', 'dog', 'monkey']for animal in animals: print(animal)
通过循环的方式,对列表中的元素快速变换,进行快速操作形成新的列表。举个例子:nums = [0, 1, 2, 3, 4]squares = []for x in nums: squares.append(x ** 2)print(squares) # Prints [0, 1, 4, 9, 16]
第六步的代码可以简化成:nums = [0, 1, 2, 3, 4]squares = [x ** 2 for x in nums]print(squares) # Prints [0, 1, 4, 9, 16]
循环的时候列表还可以加条件语句:nums = [0, 1, 2, 3, 4]even_squares = [x ** 2 for x in nums if x % 2 == 0]print(even_squares) # Prints '[0, 4, 16]'