python入门
列表
排序列表元素
cars=['bwm','audi','toyota','subaru']
cars.sort()
print(cars)
- 方法sort是永久性排序,不可更改,现在是按照字母顺序
cars=['bwm','audi','toyota','subaru']
cars.sort(reverse=True)
print(cars)
- 方法sort(reverse=True),与字母顺序相反排序
print('Here is the original list')
print(cars)
print('Here is the sorted list')
print(sorted(cars))
- 函数sorted()是临时性排序,
cars=['bwm','audi','toyota','subaru']
print('Here is the original list')
print(cars)
cars.reverse()
print(cars)
- 方法reverse()是将列表元素颠倒,打印列表,不能直接打印方法,修改完了就完了
cars=['bwm','audi','toyota','subaru']
len(cars)
print(len(cars))
- 方法len()来确定列表长度
遍历
magicians=['alice','david','carolina']
for magician in magicians:
print(magician)
- 遍历整个列表,不要忘记冒号。python将magicians中的第一个值存储到magician中
magicians=['alice','david','carolina']
for magician in magicians:
print(magician+"\n")
print('Thank you!')
- 缩进的才能循环
for value in range(1,5):
print(value)
- 创建数值列表, range(1,5)表示从1开始到5结束,不包括5
numbers=list(range(1,5))
print(numbers)
- 使用函数list()来生成列表
range(2,11,2)
- 表示从2开始到11结束,不断的加2