python 列表操作
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
bicycle = bicycles(n-1);
bicycle = bicycles(-1);
bicycles.append('feige')
bicycles.insert(n-1, 'long')
del bicycles(n-1)
bicycle = bicycles.pop()
print(bicycle); ==> specialized
bicycle = bicycles.pop(n-1)
bicycle = 'cannondale'
bicycles.remove(bicycle)
正向(由小到大)
bicycles.sort()
负向(由大到小)
bicycles.sort(reverse=True)
正向(由小到大)
sorted(bicycles)
负向(由大到小)
sorted(bicycles, reverse=True)
bicycles.reverse()
len(bicycles)
for bicycle in bicycles:
#doSomeThing with bicycle
#doSomeThing after loop
ps:注意缩进和冒号(:)
moterbicycles = bicycles[n:m]
注:
1.截取的是从第n+1个元素开始,到第m个元素为止(包含第m个元素)
2.n为空时,表示从开始截取;m为空时,表示截取到末尾
3.n和m可以为负值,表示倒序截取(从倒数第m+1个元素到倒数第n个)
4.输出时总是依照原数列从前到后输出
5.n的绝对值总是大于m
for num in range(n,m,k):
#doSomeThing with num
#doSomeThing after loop
OR
nums = range(n,m,k)
for num in nums:
#doSomeThing with num
#doSomeThing after loop
获取的值从n开始,依次加k(无参数k时默认为1),到m-1为止(含首不含尾)
注:使用range()时需要循环取值,如果直接使用下面的代码是取不到值的
nums = range(1,9)
print(nums) ==> range(1, 9)
需要输出nums时,使用如下方式
nums = list(range(1,9))
print(nums) ==> [1, 2, 3, 4, 5, 6, 7, 8]
最大值:max(nums)
最小值:min(nums)
求和:sum(nums)
squares = [value**2 for value in range(1,11)]
print(squares)
==> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
dimensions = (100,50)
注:
1.元组的值不能单个修改,修改值相当于重新给元组赋值
2.元组可以for遍历