2017.5.3 操作列表

1. for循环

for magician in magicians:  #这里注意for循环后面有一个冒号

     print(magician) #以及print这一行前面必须有空格,类似\t

打印出来的结果分为多行

pizzas = ['pepper','chicken','fruit']

for pizza in pizzas:

     print("I like " + pizza + "pizza!")

print("I really like pizzas!")  #在循环结束后的末尾输出一行

pizzas = ['pepper','chicken','fruit']

for pizza in pizzas:

      print("I like " + pizza + "pizza!")

      print("I really like pizzas!")  #在每一行输出都加上一行

pizzas = ['pepper','chicken','fruit']

for pizza in pizzas:

       print("I like " + pizza + "pizza!")

print("I really like " + pizza + " pizza!")  #这里会输出最后一个pizza的名字但是不会报错

2. 创建数值列表

使用函数range():

for value in range(1,6):

      print(value) #打印1-5这5个数字,从第一个数开始数,但是不包括第二个数

输出列表:

even_numbers = list(range(2,11,2))  #这里range从2开始,加2递增,到小于11结束

print(even_numbers)  #输出[2,4,6,8,10] #list的作用是将上述结果转换为列表

squares = []

for value in range(1,11):

      squares.append(value ** 2)  #输出从1~10的平方

print(squares)

3. 切片

players = ['charles','martina','michael','florence','eli']

print(players[0:3])  #截取从0开始,到索引3结束(不包括索引3)

print(players[1:4]) #从索引1开始,到索引4结束(不包括索引4)

print(players[:4]) #从索引0开始,到索引4结束(不包括索引4)

print(players[2:]) #从索引2开始,到最后一个元素

print(players[-3:])

for player in players[:3]: #遍历前三个列表

      print(player.title())

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

friend_foods = my_foods[:] #复制my_foods到friend_foods列表中

print(friend_foods) #不能使用friend_foods = my_foods直接进行复制

4. 元组

元组中的值是不能被修改的。

dimensions = (200,50,70,30,'test')

print(dimensions[0])

print(dimensions[1])

print(dimensions[-1])  #其他定义类似列表的定义

dimensions[0] = 40  #不能赋值 会报错 TypeError: 'tuple' object does not support item assignment

print(dimensions[0])

for dimension in dimensions:

print(dimension)  #元组的遍历

dimensions = ('a','b','c')

print(dimensions)  #dimensions中的元素不可以单独赋值,但是可以整个修改dimensions

你可能感兴趣的:(2017.5.3 操作列表)