for loop
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}.\n")
print("Thank you, everyone. That was a great magic show!")
numerical lists
range()
# 1,2,3,4
for value in range(1, 5):
print(value)
# 0,1,2,3,4
for value in range(5):
print(value)
用list()函数将range结果转换为list
numbers = list(range(2, 5))
print(numbers)
设置步长
even_numbers = list(range(2, 11, 2))
print(even_numbers)
# 2, 4, 6, 8, 10
数学统计
>>> digits = [1,2,3,4,5,6,7,8,9]
>>> min(digits)
1
>>> max(digits)
9
>>> sum(digits)
45
list comprehensions
squares = [value ** 2 for value in range(1, 11)]
print(squares)
# 等价于
squares = []
for value in range(1, 11):
squares.append(value ** 2)
Working with Part of a List
slice
fruits = ['apple', 'banana', 'orange', 'pineapple', 'pear', 'plum']
print(fruits[1:4]) # index 1, 2, 3
print(fruits[2:]) # index 2到最后
print(fruits[:4]) # index 0到3
print(fruits[-3:]) # 最后3个
print(fruits[1:4:2]) # 第三个参数为步长,默认为1 index 1, 3
print(fruits[-3::-1]) # 步长为负数则反向 ['pineapple', 'orange', 'banana', 'apple']
print(fruits[:]) # 复制整个list
Tuples元组
元组不可修改 an immutable list is called a tuple
如果声明只有一个值的tuple,需要加逗号
my_t = (1,)
print(my_t[0])
Styling Your Code
- 用4个空格缩进
- 每行不超过79个字符
- 不要过度使用空行