python学习笔记: 第四章 操作列表

󰃭 2017-04-03

学习笔记 第四章


打印列表中的所有元素

magicians = ['alice', 'david', 'carolina']
for magician in magicians:
    print(magician)
    print(magician.title() + ", that was a great trick!")
    print("I can't wait to see your next trick, " + magician.title() + ".\n")

print("Thank you, everyone. That was a great magic show!")

使用range()生成list

for value in range(1,5):
    print(value)

数字列表的生成

numbers = list(range(1,6))
print(numbers)

偶数列表

even_numbers = list(range(2,11,2))
print(even_numbers)

空列表填充数字

squares = []
for value in range(1,11):
    square = value ** 2
    squares.append(square)
print(squares)

列表统计处理

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(min(digits),max(digits),sum(digits))

列表解析

squares = [value**2 for value in range(1,10)]
print(squares)

切片

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])

遍历切片

for player in players[:3]:
    print(player.title())

复制列表

[]是必须的,表示复制一个列表,而不是定义一个参数指向原始列表。

my_foods = ['pizza', 'falafel', 'carrot cake']
#friend_foods = my_foods
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)
my_foods.append('cannoli')
friend_foods.append('ice cream')
print(my_foods)
print(friend_foods)

元组

不可变的列表,采用圆括号表示

dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
for dimension in dimensions:
    print(dimension)

元组里的元素不可修改,如:dimensions[0] = 250, 错误! 但是元组可以修改,把整个元组看做一个变量,如:

dimensions = (200, 50)
print(dimensions)
dimensions = (250, 100)
print(dimensions)

格式

4空格缩进、每行不超过80字符。