Python day_2

1.for遍历列表

for A in B :
将B列表中的元素储存到A列表中

 magicians = ['alice', 'david', 'carolina'] 
for magician in magicians: 
print(magician) 
alice 
david 
carolina

Python根据缩进来判断代码行与前一个代码行的关系。

在for A in B:后进行缩进,缩进部分也会参加循环

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 trick, Carolina. 
2.range() 生成一串数
for value in range(1,5): 
 print(value) 
1 
2 
3 
4 

在这个示例中,range()只是打印数字1~4,这是你在编程语言中经常看到的差一行为的结果。
函数range()让Python从你指定的第一个值开始数,并在到达你指定的第二个值后停止,因此输出
不包含第二个值(这里为5).

3.list(range(num_1,num_2))range()做list()的参数,可生成列表
numbers = list(range(1,6)) 
print(numbers) 
[1, 2, 3, 4, 5] 

range还有一种操作

4. range(num_1,num_2,num_3)

使用函数range()时,还可指定步长。
列表中的数a
num_1<=a<=num_2,num_3为他们的等差值

even_numbers = list(range(2,11,2)) 
print(even_numbers) 
[2, 4, 6, 8, 10] 
5.对数字列表执行简单的统计计算
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0 
>>> max(digits)
9 
>>> sum(digits)
45 
6.列表解析
squares = [value**2 for value in range(1,11)] 
print(squares) 

要使用这种语法,首先指定一个描述性的列表名,如squares;然后,指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值。在这个示例中,表达式为value** 2,它计算平方值。接下来,编写一个for循环,用于给表达式提供值,再加上右方括号。在这个示例中,for循环为for value in range(1,11),它将值1~10提供给表达式value**2。请注意,这里的for语句末尾没有冒号.

7.切片
players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[0:3]) 
['charles', 'martina', 'michael'] 

与range类似,给末尾值时要加一
如果你没有指定第一个索引,Python将自动从列表开头开始
要让切片终止于列表末尾,也可使用类似的语法。
无论列表多长,这种语法都能够让你输出从特定位置到列表末尾的所有元素。负数索引返回离列表末尾相应距离的元素,因此你可以输出列表末尾的任何切片。例如,如果你要输出名单上的最后三名队员,可使用切片players[-3:]:

players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
print(players[-3:]) 
8.遍历切片
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 
9.复制切片
 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) 
My favorite foods are: 
['pizza', 'falafel', 'carrot cake'] 
My friend's favorite foods are: 
['pizza', 'falafel', 'carrot cake'] 

要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])。
这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。

10.元组

在python中,试图修改元组的操作是被禁止的。
定义元组用括号

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值