python的基础04 操作列表

4.1 遍历整个列表

magicians = ['alice','david','carolina'] # 定义了一个列表
for magician in magicians:  # 定义了一个for循环
'''这行代码让python从列表migicians中取出一个值,并将这个值存储在了变量magician里面'''
    print(magician)  # python会打印出存储在变量magician中的每一个值
alice
david
carolina
 

4.1.1 深入地研究循环

magicians = ['alice','david','carolina']
for magician in magicians:
    print(magician) 
  • 上面代码解读
    • 第一行我们定义了一个列表
    • for magician in magicians:这行代码让python获取列表magicians里的第一个值('alice'),并将其存储到了变量magician中
    • 然后,python会读取下一行代码,print(magician),打印出变量magician的值
    • 因为列表中还有其它的元素,所以python又返回到循环的这一行for magician in magicians:,python会获取列表的第二个值('david'),并将它存放在变量magician中,在执行下面的print(magician).
    • python再次执行for magician in magicians:,把第三个值放在变量magician中,打印出第三个值.
    • 列表中没有其它值了,所以这个循环才会结束,python才会继续执行下面的代码.
 

4.1.2 在for循环中执行更多的操作

# for循环练习
magicians = ['alice','david','carolina']
for magician in magicians:
# 在for循环中,想包含多少行代码都可以,只是后面属于循环的代码都要使用同一个等级的缩进
    print(magician + ',' + "that was a great trick!")
    print("I can't wait to see your next trick" + ',' + magician + '.')
alice,that was a great trick!
I can't wait to see your next trick,alice.
david,that was a great trick!
I can't wait to see your next trick,david.
carolina,that was a great trick!
I can't wait to see your next trick,carolina.
 

4.1.3 在for循环结束后执行一些操作

  • 在for循环后面,没有缩进的代码都只执行一次,不会重复执行.
 
magicians = ['alice','david','carolina']
for magician in magicians:
    print(magician + ',' + "that was a great trick!")
    print('I can\'t wait to see your next trick' + ',' + magician + '.\n')
print("Thank you,everyone.That was a great magic show!")
alice,that was a great trick!
I can't wait to see your next trick,alice.

david,that was a great trick!
I can't wait to see your next trick,david.

carolina,that was a great trick!
I can't wait to see your next trick,carolina.

Thank you,everyone.That was a great magic show!
 

动手试一试

 
# 4-1 比萨:想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用 for循环将每种比萨的名称都打印出来。
pizzas = ['New York Style','Pan Pizza','Thick style']
for pizza in pizzas:
    print(pizza)
print('\n')
    
#  修改这个 for 循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出,如“ I like pepperoni pizza”。
pizzas = ['New York Style','Pan Pizza','Thick style']
for pizza in pizzas:
    print("I like" + ' ' + pizza)
print('\n')
#  在程序末尾添加一行代码,它不在 for 循环中,指出你有多喜欢比萨。输出应包含针对每种比萨的消息,还有一个总结性句子,如“ I really love pizza!”。
pizzas = ['New York Style','Pan Pizza','Thick style']
for pizza in pizzas:
    print("I like" + ' ' + pizza)
print("I really love pizza!")
New York Style
Pan Pizza
Thick style

I like New York Style
I like Pan Pizza
I like Thick style

I like New York Style
I like Pan Pizza
I like Thick style
I really love pizza!
 
#4-2 动物:想出至少三种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用 for 循环将每种动物的名称都打印出来。
animals = ['cat','dog','monkey']
for animal in animals:
    print(animal)
print('\n')

#  修改这个程序,使其针对每种动物都打印一个句子,如“ A dog would make a greatpet”。
animals = ['cat','dog','monkey']
for animal in animals:
    print("A",animal,"would make a great pet.")
print("\n")

#  在程序末尾添加一行代码,指出这些动物的共同之处,如打印诸如“ Any of theseanimals would make a great pet!”这样的句子。
animals = ['cat','dog','monkey']
for animal in animals:
    print("A",animal,"would make a great pet.")
print("Any of theseanimals would make a great pet!")
cat
dog
monkey

A cat would make a great pet.
A dog would make a great pet.
A monkey would make a great pet.

A cat would make a great pet.
A dog would make a great pet.
A monkey would make a great pet.
Any of theseanimals would make a great pet!
 

4.3 创建数值列表

4.3.1 使用函数range()

  • 函数range()可以轻松的让我们生成一系列数字.
  • 函数range()让python从我们指定的位置开始数,并在到达我们指定的第二个值时停止(也就是包含左边不包含右边)
for value in range(1,6):
    print(value)
1
2
3
4
5

4.3.2 使用range()创建数字列表

  • 要创建数字列表,可使用函数list()将rang()的结果直接转化为列表,把rang()作为list()的参数.
# 打印出1-5
numbers = list(range(1,6))
print(numbers)

# 打印出5-23的所有基数或者偶数
number = list(range(5,24,2))
# 函数range()从5开始数,然后不断的+2,直到达到23
print(number)
number = list(range(6,24,2))
# 函数range()从6开始数,不断地+2,直到到达23
print(number)
[1, 2, 3, 4, 5]
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
[6, 8, 10, 12, 14, 16, 18, 20, 22]
 
# 打印出1-10的平方,使用for循环
numbers = list(range(1,11))  # 生成包含1-10的列表numbers
for number in numbers:  # 从列表numbers中取出值放入变量number里面
#end = '空格'表示print完结后不换行,输出一个空格,接着输出print里面需要打印的内容
    print(number ** 2,end=' ')  # 打印出变量number平方的值 

# 打印出1-10的平方,并把结果放在列表里面
print('\n')
squares = []
for  square in range(1,11):
    squares.append(square ** 2)
print(squares)
1 4 9 16 25 36 49 64 81 100 

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
 

4.3.3 对数字列表执行简单的统计计算

  • 有几个用于专门处理数字列表的python的函数可以让我们轻松的找到列表的最大值丶最小值和总和
# min()获取最小值,max()获取最大值,sum()获取所有元素的和
digits = [1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
0
9
45

4.3.4 列表解析

  • 列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素.
    • 要使用这种语法:
      • 1.指定一个列表名称
      • 2.指定一个左方括号,并定义一个表达式,用于生成我们要存储到列表中的值
      • 3.编写一个for循环,用于给表达式提供值,在加上右方括号,for语句结束没有冒号(:)
 
squares = [value ** 2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
 

动手试一试 

# 4-3 数到 20:使用一个 for 循环打印数字 1~20(含)。
for number in range(1,21):
    print(number,end = ' ')
    
# 4-4 一百万:创建一个列表,其中包含数字 1~1 000 000,再使用一个 for 循环将这些数字打印出来(如果输出的时间太长,按 Ctrl + C 停止输出,或关闭输出窗口)。
numbers = list(range(1,1000001))
# print(numbers)
'''4-5 计算 1~1 000 000 的总和:创建一个列表,其中包含数字 1~1 000 000,再使用min()和 max()核实该列表确实是从 1 开始,到 1 000 000 结束的。另外,对这个列表调
用函数 sum(),看看 Python 将一百万个数字相加需要多长时间。'''
numbers = list(range(1,1000001))
print(sum(numbers))
print(max(numbers))
print(min(numbers))

# 4-6 奇数:通过给函数range()指定第三个参数来创建一个列表,其中包含 1~20 的奇数;再使用一个 for 循环将这些数字都打印出来。
numbers = list(range(1,21,2))
for number in numbers:
    print(number,end = ' ')

# 4-7 3 的倍数:创建一个列表,其中包含 3~30 内能被 3 整除的数字;再使用一个 for循环将这个列表中的数字都打印出来。
numbers = list(range(3,31,3))
for number in numbers:
        print(number,end = ' ')
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 500000500000
1000000
1
1 3 5 7 9 11 13 15 17 19 3 6 9 12 15 18 21 24 27 30 
 
'''4-8 立方:将同一个数字乘三次称为立方。例如,在 Python 中, 2 的立方用 2**3
表示。请创建一个列表,其中包含前 10 个整数(即 1~10)的立方,再使用一个 for 循
环将这些立方数都打印出来。'''
nums = list(range(1,11))
for num in nums:
    print(num ** 3,end = ' ')

# 4-9 立方解析:使用列表解析生成一个列表,其中包含前 10 个整数的立方。
print("\n")
nums = [num ** 3 for num in range(1,11)]
print(nums)
1 8 27 64 125 216 343 512 729 1000 

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
 

4.4 使用列表的一部分

4.4.1 切片

  • 要创建切片,可指定要使用的第一个元素和最后一个元素的索引.
  • 和range()一样,也是包含左边不包含右边
players = ['charles','martina','michale','florence','eli']
# 打印出列表的所有元素
print(players)
# 打印出列表的前3个元素
print(players[0:3])
# 打印出列表的第2-4个元素
print(players[1:4])
# 如果没有指定第一个索引,将会从头开始打印到指定的第二个元素停止
print(players[:2])
# 如果没有指定第二个索引,将会从指定位置打印到最后一个元素
print(players[2:])
['charles', 'martina', 'michale', 'florence', 'eli']
['charles', 'martina', 'michale']
['martina', 'michale', 'florence']
['charles', 'martina']
['michale', 'florence', 'eli']
 

4.4.2 遍历切片

  • 如果要遍历列表的部分元素,可以在for循环中使用切片
players = ['charles','martina','michael','florence','eli']
print("Here are the first three players on my team:")
for player in players[0:3]:
    print(player.title())
Here are the first three players on my team:
Charles
Martina
Michael
 

4.4.3 复制列表

  • 要复制列表,可创建一个包含整个列表的切片,同时省略起始索引和终止索引([:])
my_foods = ['pizza','falafel','carrot cake']
# 复制列表
friend_foods = my_foods[:]
print(friend_foods)
# 像复制的列表末尾添加一个元素'ice cream
friend_foods.append("ice cream")
# 打印列表,不会影响另一个列表
print(friend_foods)
print(my_foods)
['pizza', 'falafel', 'carrot cake']
['pizza', 'falafel', 'carrot cake', 'ice cream']
['pizza', 'falafel', 'carrot cake']
 

动手试一试

'''4-10 切片:选择你在本章编写的一个程序,在末尾添加几行代码,以完成如下任务。
 打印消息“ The first three items in the list are:”,再使用切片来打印列表的前三个
元素。'''
players = ['charles','martina','michale','florence','eli']
print("The first three items in the list are:",end = '')
print(players[0:3])

#  打印消息“ The last three items in the list are:”,再使用切片来打印列表末尾的三个元素。
print(players[-3:-1])

# 4-11 你的比萨和我的比萨:在你为完成练习 4-1 而编写的程序中,创建比萨列表的副本,并将其存储到变量 friend_pizzas 中,再完成如下任务。
pizzas = ['New York Style','Pan Pizza','Thick style']
friend_pizzas = pizzas[:]
#  在原来的比萨列表中添加一种比萨。
pizzas.append('Chicago Style')
# 在列表 friend_pizzas 中添加另一种比萨。
friend_pizzas.append('California Style')

''' 核实你有两个不同的列表。为此,打印消息“ My favorite pizzas are:”,再使用一个 for 循环来打印第一个列表;打印消息“ My friend’s favorite pizzas are:”,再使
用一个 for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。'''
print('\n')
print(pizzas)
print(friend_pizzas)

print('\n')
print("My favorite pizzas are:")
for pizza in pizzas:
    print(pizza)

print('\n')
print("My friend's favorite are:")
for friend_pizza in friend_pizzas:
    print(friend_pizza)
The first three items in the list are:['charles', 'martina', 'michale']
['michale', 'florence']

['New York Style', 'Pan Pizza', 'Thick style', 'Chicago Style']
['New York Style', 'Pan Pizza', 'Thick style', 'California Style']

My favorite pizzas are:
New York Style
Pan Pizza
Thick style
Chicago Style

My friend's favorite are:
New York Style
Pan Pizza
Thick style
California Style

4.5 元组

  • python里面,我们把不能修改的值称为不可变的,而不可变的列表被称之为元组.

    4.5.1 定义元组

  • 元组看起来犹如列表,但使用圆括号()而不是方括号标识
dimensions = (200,50) # 定义了一个元组,使用的是圆括号而不是方括号
print(dimensions[1])  # 打印出元组的第2个元素
print(dimensions[0])
50
200
 

4.5.2 遍历元组中的所有值

  • 像列表一样,也可以使用for循环来遍历元组中的所有值
dimensions = (200,50)
for dimension in dimensions:
    print(dimension)
200
50
 

4.5.3 修改元组变量

  • 虽然不可以修改元组的元素,但是我们可以给存储元组的变量赋值.
dimensions = (200,50)
print(dimensions)
dimensions = (400,100)
print(dimensions)
(200, 50)
(400, 100)

猜你喜欢

转载自www.cnblogs.com/Pythonahy/p/10223013.html