码迷,mamicode.com
首页 > 编程语言 > 详细

python编程:从入门到实践----第四章>操作列表

时间:2020-02-18 17:59:58      阅读:23      评论:0      收藏:0      [点我收藏+]

标签:git   next   alice   大写   额外   换行符   cte   不包含   typeerror   

一、遍历整个列表

1-1.假设有一个魔术师名单,需要将其中每个魔术师的名字都打印出来。

# 用for循环来打印魔术师名单中的名字
magicians=[‘alice‘,‘david‘,‘carolina‘]
for magician in magicians:      #这里面的magician和magicians是便于让读者得知for循环在哪个列表中进行遍历
    print(magician)

#输出结果:
alice
david
carolina

 解析以上代码:

a. 先定义一个列表

b. 定义一个for循环:从列表magicians中取出一个名字,并将其存储在变量magician中

c. 让python打印前面存储到变量magician中的名字

d. 重复执行for循环并打印出来

 

1-2. 假设有一个魔术师名单,需要将所有魔术师打印出来,并且每个名字后面打印一条消息:指出他的表演太精彩。

magicians=[‘alice‘,‘david‘,‘carolina‘]
for magician in magicians:
    print(magician.title() + ",that was a great trick!")

#输出结果:
Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!

 解析以上代码:

a. 先定义一个列表

b. 定义一个for循环:从列表magicians中取出一个名字,并将其存储在变量magician中

c. 让python打印前面存储到变量magician中的名字,用title方法让每个名字第一个字母大写,并用(+)拼接后面的语句

d. 重复执行for循环并打印出来

 

1-3.假设有一个魔术师名单,需要将所有魔术师打印出来,并且每个名字后面打印一条消息:指出他的表演太精彩。在最后一行代码下面加一行代码,告诉每位魔术师,我们期待他的下一次表演

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

#输出结果:
Alice,that was a great trick!
I can‘t wait to see your next trickAlice.

David,that was a great trick!
I can‘t wait to see your next trickDavid.

Carolina,that was a great trick!
I can‘t wait to see your next trickCarolina.

 解析以上代码:

a. 由于两条print语句都缩进了,因此它们都将针对列表中的每位魔术师执行一次

b. 第二条print语句中的换行符“\n”:在每次迭代结束后插入一个空行

 

1-4. for循环的结束:在第3个实例中加入一条向全体魔术师致谢的消息,感谢他们的精彩表演。

magicians=[‘alice‘,‘david‘,‘carolina‘]
for magician in magicians:
    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!")

#输出结果:
Alice,that was a great trick!
I can‘t wait to see your next trickAlice.

David,that was a great trick!
I can‘t wait to see your next trickDavid.

Carolina,that was a great trick!
I can‘t wait to see your next trickCarolina.

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

 解析以上代码:

a.for循环后面,没有缩进的代码都只执行一次,而不会重复执行。第三条print语句没有缩进,因此只执行一次

 

二、避免缩进错误

1.忘记缩进:对于for语句后面且属于循环组成部分的代码行,一定要缩进。如果没有缩进报错:IndentationError: expected an indented block

magicians=[‘alice‘,‘david‘,‘carolina‘]
for magician in magicians:
print(magician.title() + ",that was a great trick!")

#输出结果:
IndentationError: expected an indented block

2.忘记缩进额外的代码行。如下面的代码,并没有按照1-3的需求来执行

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

#输出结果:
Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!
I can‘t wait to see your next trickCarolina.

3. 不必要的缩进:以下代码的print不属于前一行代码,所以不需要缩进

message ="Hello Python World!"
    print(message)

#输出结果:IndentationError: unexpected indent

4. 循环后不必要的缩进:本该执行for循环结束的语句,进行了缩进,代码就重复执行三次

magicians=[‘alice‘,‘david‘,‘carolina‘]
for magician in magicians:
    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!")

#输出结果:
Alice,that was a great trick!
I can‘t wait to see your next trickAlice.

Thank you,everyone.That was a great magic show!
David,that was a great trick!
I can‘t wait to see your next trickDavid.

Thank you,everyone.That was a great magic show!
Carolina,that was a great trick!
I can‘t wait to see your next trickCarolina.

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

5. 遗漏冒号:for语句末尾的冒号是告知python,下一行是循环的第一行

magicians=[‘alice‘,‘david‘,‘carolina‘]
for magician in magicians
    print(magician.title() + ",that was a great trick!")

#输出结果:SyntaxError: invalid syntax

 

三、创建数值列表

 1.使用函数range( ):轻松生成一系列的数字。函数range指定第一个值开始数,并到达指定第二个值后停止,因此输出不包含第二个值。

    如果range输出不符合预期,可以尝试指定的值加1或减1.

for value in range(1,5):
    print(value)
#输出结果:
1
2
3
4

2. 使用range( )创建数字列表

 a.要创建数字列表,可使用函数list( )将range( )的结果直接转换为列表。如果将range( )作为list( )的参数,输出将为一个数字列表。

even_numbers = list(range(2,11,2))     #第一个2指的是从2开始数;最后一个2指的是步长,也就是每次叠加需要增加2,知道达到或超过终值11
print(even_numbers)

#输出结果:[2, 4, 6, 8, 10] 

 b. 用range创建:前10个整数(1~10)的平方

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

#输出结果:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 解析以上代码:

a. 创建一个空列表

b. 使用函数range( )让python遍历1~10的值

c. 在循环中,计算当前值得平方,并将结果存储到变量square中

d. 将新计算得到的平方值附加到列表squares末尾

e. 循环结束,打印列表squares

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

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

#输出结果:
0
9
45

4. 列表解析

squares = [value**2 for value in range(1,11)]
print(squares)
#输出结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 解析以上代码:

a. 指定一个列表名

b.定义一个表达式,用来生成要存储的列表的值,如上面的value**2

c. 编写一个for循环,用于给表达式提供值。如上面的for value in range(1,11),它将值1~10提供给表达式value**2。这里的for循环末尾不需要冒号

备注:如果需要些三四行代码来生成繁复的列表时,可以考虑创建列表解析

 

四、使用列表的一部分

1. 切片:指定要使用的第一个元素和最后一个元素的索引,到达指定的第二个索引前面的元素后停止。

players = [‘charles‘,‘martina‘,‘michael‘,‘florence‘,‘eli‘]
print(players[1:4])     #打印前三名
print(players[:4])      #打印前四名,没有指定第一个元素就从头开始取值
print(players[2:])      #打印后三名,没有指定第二个元素就打印到结尾

#输出结果:
[‘martina‘, ‘michael‘, ‘florence‘]
[‘charles‘, ‘martina‘, ‘michael‘, ‘florence‘]
[‘michael‘, ‘florence‘, ‘eli‘]

2. 遍历切片:遍历前三名队员,并打印他们的名字

players = [‘charles‘,‘martina‘,‘michael‘,‘florence‘,‘eli‘]
print("Here are the first three players on my team:")
for player in players[:3]:
    print(player.title())
#输出结果:
Here are the first three players on my team:
Charles
Martina
Michael

3. 复制列表:用同时省略起始索引和终止索引([ : ])的方法来实现,这个方法是创建一个适于第一个元素,终止于最后一个元素的切片,即复制整个列表。

my_foods=[‘pizza‘,‘falafel‘,‘carrot‘,‘cake‘]
friend_foods = my_foods[:]
my_foods.append(‘cannoli‘)
friend_foods.append(‘ice cream‘)
print("My favorite foods are:")
print(my_foods)
print("\nMy friend‘s favorite foods are:")
print(friend_foods)

#输出结果:
My favorite foods are:
[‘pizza‘, ‘falafel‘, ‘carrot‘, ‘cake‘, ‘cannoli‘]

My friend‘s favorite foods are:
[‘pizza‘, ‘falafel‘, ‘carrot‘, ‘cake‘, ‘ice cream‘]

 解析以上代码:

a.my_foods的元素赋值到新列表friend_foods中,也就是将副本存储到friend_foods中

b. 在列表my_foods中添加“cannoli”

c. 在列表friend_foods中添加“ice cream”

d. 最后打印这两个列表

 

五、元组

1.定义元组:使用圆括号标识。定义元组后,就可以使用索引来访问元素,就想访问列表元素一样。元组里面的元素不能修改

dimensions = (200,50)
print(dimensions[0])
dimensions[0] =250
print(dimensions[0])

#输出结果:
200
TypeError: ‘tuple‘ object does not support item assignment     #由于元组中的元素不能修改,所以第二个打印报错

2. 遍历元组中的所有值:像列表一样使用for循环

dimensions = (200,50)
for dimension in dimensions:
    print(dimension)

#输出结果:
200
50

3. 修改元组变量:虽然不能修改元组的元素,但可以给存储元组的变量赋值。

dimensions = (200,50)
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)

dimensions= (400,100)
print("\nModified dimensions:")
for dimension in dimensions:
    print(dimension)

#输出结果:
Original dimensions:
200
50

Modified dimensions:
400
100

  

备注:此内容从《python编程:从入门到实践》中摘录

 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

python编程:从入门到实践----第四章>操作列表

标签:git   next   alice   大写   额外   换行符   cte   不包含   typeerror   

原文地址:https://www.cnblogs.com/heiqiuxixi/p/12322618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有 京ICP备13008772号-2
迷上了代码!