遍历列表
names=['yang','liu','Qian','zhang','Zhai']
for name in names:
print(name)
for name in names:
print(name.title()+" is my best friend!")
print("You are so lovely ,"+name.title()+"!")
print("Thank you,everyone")
输出结果
yang
liu
Qian
zhang
Zhai
Yang is my best friend!
You are so lovely ,Yang!
Liu is my best friend!
You are so lovely ,Liu!
Qian is my best friend!
You are so lovely ,Qian!
Zhang is my best friend!
You are so lovely ,Zhang!
Zhai is my best friend!
You are so lovely ,Zhai!
Thank you,everyone
数字列表
- range函数可以生成一系列的数字
- 使用list函数将range生成的结果生成列表
for value in range(1,5):
print(value)
numbers=list(range(1,5))
print(numbers)
numbers=list(range(2,11,2))
print(numbers)
squares=[]
for value in range(1,5):
squares.append(value**2)
print(squares)
print(min(squares))
print(max(squares))
print(sum(squares))
输出结果
1
2
3
4
[1, 2, 3, 4]
[2, 4, 6, 8, 10]
[1, 4, 9, 16]
1
16
30
列表切片
-
其中name=names[:],是新建立一个列表
-
name0=names,是让两个变量都指向一个列表,本质上还是一个列表
names=['Yang','Liu','Qian','Zhang','Zhai']
print(names[1:3])
print(names[:3])
print(names[3:])
print(names[-3:])
print(names[:])
for name in names[:3]:
print(name)
name2=names[:]
name0=names
print(names)
print(name2)
print(name0)
names.append('Xiao')
print(names)
print(name2)
print(name0)
输出结果
['Liu', 'Qian']
['Yang', 'Liu', 'Qian']
['Zhang', 'Zhai']
['Qian', 'Zhang', 'Zhai']
['Yang', 'Liu', 'Qian', 'Zhang', 'Zhai']
Yang
Liu
Qian
['Yang', 'Liu', 'Qian', 'Zhang', 'Zhai']
['Yang', 'Liu', 'Qian', 'Zhang', 'Zhai']
['Yang', 'Liu', 'Qian', 'Zhang', 'Zhai']
['Yang', 'Liu', 'Qian', 'Zhang', 'Zhai', 'Xiao']
['Yang', 'Liu', 'Qian', 'Zhang', 'Zhai']
['Yang', 'Liu', 'Qian', 'Zhang', 'Zhai', 'Xiao']
元组
- 元组使用圆括号标识,但是其中的值是不可以修改的。
number=(20,5)