第四章 操作列表

for 循环

知识点

示例:

magicians = ['alan','banch','caln']
for magican in magicans:
    print(magican)

注意点:for 循环后面需要加冒号,所有在for 循环程序体中的内容都需要缩进

作业

animals = ['lion', 'cat', 'dog']
for animal in animals:
    print(animal)
    print('A '+ animal+' would make a great pet')
print("Any of these animals would make a great pet!")

数值列表

知识点

使用函数range( )来创建数字,配合list()来创建数字列表。

numbers = list(range(1,6))
print(numbers)
结果如下:
[1,2,3,4,5]

作业

4.3

for number in range(1,21):
    print(number)

4.4

numbers = list(range(1,1000001))
for number in numbers:
    print(number)

4.5

numbers = list(range(1,1000001))
for number in numbers:
    print(number)
print(min(numbers),max(numbers),sum(numbers))

4.6

jis = list(range(1,21,2))
for ji in jis:
    print(ji)
print('完成\n')

4.7

zhengchus = list(range(3,31,3))
for zhengchu in zhengchus:
    print(zhengchu)
print('完成\n')

4.8

cengfangs = []
for value in range(1,11):
    cengfang = value**3
    cengfangs.append(cengfang)
print(cengfangs)

4.9

cengfangs = [value**3 for value in range(1,11)]
print(cengfangs)

使用列表的一部分

知识点

切片

players = ['a','b','c','d','e']
print(players[0:3])

结果
['a','b','c']

复制列表

my_foods = ['pizza','falafel','carrot']
friends_foods = my_foods[:]

my_foods.append('cannoli')
friends_foods.append('ice')

作业

4.10

jis = list(range(1,21,2))
print(jis)
print('the first three items in the list are:')
print(jis[:3])
print('Three items form the middle of the list are')
print(jis[4:7])
print('The last three items in the list are:')
print(jis[-3:])

4.11

animals = ['lion', 'cat', 'dog']
friend_animals = animals[:]
animals.append('fox')
friend_animals.append('pig')
print('My favorite animals are:')
for animal in animals:
    print(animal)
print('My friend favorite animals are:')
for friend_animal in friend_animals:
    print(friend_animal)

元组

和列表类似,不过使用的是原括号,不是方括号,不能修改元组里面的值,但可以给变量重新赋值。