Python-3 操作列表

本文深入探讨Python中列表和元组的使用技巧,包括遍历列表、创建数字列表、执行统计计算、使用切片、复制列表以及元组的基本操作。通过实际代码示例,读者可以快速掌握这些数据结构的高效利用方法。

遍历整个列表

Sample code as below:

magicians = ['alice', 'david','carolina']
for magician in magicians:
	print(magician) #print位置需Tab

Output as below:

alice
david
carolina

对每个元素执行操作:
Sample code as below:

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

Output as below:

Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!

如果在第一个print下一行加入同样的print,会出现什么情况?

 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")

Output as below:

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.

会发现在每一个列表中的元素执行了一遍!想跳出整个循环,只需要不缩进print即可。
Sample code as below:

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,eveyone. That wa as great magic show!") 

Output as below:

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,eveyone. That wa as great magic show!

如果开始时候print不缩进会有什么问题?
Sample code as below:

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

Output as below:

File "Learn.python", line 137
    print(magician.title()+",that was a great trick!")
        ^
IndentationError: expected an indented block

当出现这个错误时候需要缩进Tab Print 既可以消除这个错误。
切记Python for循环结尾不要遗忘" :" 冒号。

创建数字列表

  • 使用函数 range()
    Sample code as below:
 for value in range(1,5):
 	print(value)

Output as below:

1
2
3
4

使用range()时,如果输出不符合预期,请尝试+1或者-1.

  • 使用range()创建数字列表
    Sample code as below:
numbers = list(range(2,11,2))
print(numbers)

Output as below:

[2, 4, 6, 8, 10]

python中,两个星号(**)表示乘方运算。
下列为如何将前10个整数的平方加入到一个列表中:
Sample code as below:

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

Output as below:

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

如何变得更加的简洁呢?可以不使用临时变量square,直接将每个计算得到的值附加到列表末尾:
Sample code as below:

 squares = []
for value in range(1,11): 
	squares.append(value**2)
print(squares)
  • 对数字列表进行执行简单的统计计算
    Sample code as below:
digits = [1,2,3,4,5,6,7,8,9,0]
print('min =' + str(min(digits)))
print('max =' + str(max(digits)))
print('sum =' + str(sum(digits)))

Output as below:

min =0
max =9
sum =45

使用列表的一部分

  • 切片
    Sample code as below:
players = ['John','charles','martina','michael','florence','eli']
print("Players list will be ->" + str(players))
print(players[0:3]) #打印前三名成员;
print(players[1:4]) #提取列表中的2~4个元素;
print(players[:4] ) #从列表开头开始提取;
print(players[2:] ) #终止于列表结尾;
print(players[-3:]) #输出列表最后三名队员;

Output as below:

Players list will be ->['John', 'charles', 'martina', 'michael', 'florence', 'eli']
['John', 'charles', 'martina']
['charles', 'martina', 'michael']
['John', 'charles', 'martina', 'michael']
['martina', 'michael', 'florence', 'eli']
['michael', 'florence', 'eli']
  • 遍历切片
    Sample code as below:
players = ['John','charles','martina','michael','florence','eli']
print(players)
print("Here are the first three players on my team:")
for player in players[:3]: #只遍历了前三名队员:
	print(player.title())

Output as below:

['John', 'charles', 'martina', 'michael', 'florence', 'eli']
Here are the first three players on my team:
John
Charles
Martina
  • 复制列表
    需要使用到 --> [:]

Sample code as below:

my_foods = ['Pizza','falafel','carrot cake']
friend_foods = my_foods[:]

print("My favorite foods are:")
print(my_foods)

print("\nMy friend's favorite foods are: ")
print(friend_foods)

Output as below:

My favorite foods are:
['Pizza', 'falafel', 'carrot cake']
My friend's favorite foods are:
['Pizza', 'falafel', 'carrot cake'

元组

Python将不能修改的值称为不可变的,而不可变的列表成为元组。元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其他元素,就像访问列表元素一样。

Sample code as below:

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

Output as below:

200
50

尝试修改元组中的一个元素
Sample code as below:

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

Output as below:

Traceback (most recent call last):
  File "Learn.python", line 194, in <module>
    dimensions[0] = 250
TypeError: 'tuple' object does not support item assignment
  • 遍历元组中的所有值
    Sample code as below:
dimensions=(200,50)
for dimension in dimensions:
	print(dimension)

Output as below:

200
50
  • 给元组赋值是合法的:
    Sample code as below:
dimensions=(200,50)
print("Original dimensions:")
for dimension in dimensions:
	print(dimension)
dimensions=(400,100)	
print("\n Modified dimensions:")
for dimension in dimensions:
	print(dimension)

Output as below:

Original dimensions:
200
50

Modified dimensions:
400
100

本章学习了:

  • 如何高效的处理列表中的元素;
  • 如何使用for循环遍历列表;
  • 如何创建简单的数字列表;
  • 对数字列表执行一些操作;
  • 如何通过切片来使用列表的一部分和复制列表;
  • 元组的使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值