1、遍历整个列表
magicians=["alice",'wes','erd']
for magician in magicians:
print(f"{magician.title()},that was a great trick!!!")
print(f"I can not wait to see your next trick,{magician.title()}\n")
print("Thank you, everyone. That was a great magic show !!!")
2、range()
for i in range(2):
print(i)
3、range()步长
numbers=list(range(1,6,2))
print(numbers)
4、创建数值列表
squares=[]
for value in range(1,11):
square=value**2
squares.append(square)
print(squares)
5、列表中的数值比较
lists=list(range(1,11))
print(min(lists))
print(max(lists))
print(sum(lists))
6、列表的切片
players=['charles','martina','michael','flile','apple']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
切取最后3个
lists=["栗子","梨","苹果","香蕉"]
print("The first three items in the list are:")
for list in lists[-3:]:
print(list.title())
7、列表的复制与遍历
my_lists=["栗子","梨","苹果","香蕉","橙子"]
friend_lists=my_lists[:]
my_lists.append("西瓜")
friend_lists.append("草莓")
print("My favorite fruitr are:")
for my_list in my_lists[:]:
print(my_list)
print("friend favorite fruitr are:")
for friend_list in friend_lists[:]:
print(friend_list)
"""
My favorite fruitr are:
栗子
梨
苹果
香蕉
橙子
西瓜
friend favorite fruitr are:
栗子
梨
苹果
香蕉
橙子
草莓
"""
8、元组(不可变)列表适合存储在程序运行期间可能变化的数据集,元组不可变
练习4-13
自助餐=("烤肉","大虾","五花肉","烤肠")
for 吃的 in 自助餐:
print(吃的)
自助餐[0]='羊肉'
print(自助餐)
"""
烤肉
大虾
五花肉
烤肠
Traceback (most recent call last):
File "C:\Users\fly\Desktop\python_work\第四章.py", line 91, in <module>
自助餐[0]='羊肉'
TypeError: 'tuple' object does not support item assignment
"""
|