一。遍历整个列表
注意缩进,与不要遗漏冒号。
magicians = ['alice', 'david', 'carolina'] for magician in magicians: #print(magician) print(f"{magician.title()}, that waw a great trick!") print(f"I can't wait to see your next trick, {magician.title()}.\n") print("Thank you, everyone. That waw a great magic show!") print("This is test indentationError: unexpected indent")
二。创建数值列表
# 创建数值列表--实际最大输出4 for value in range(1, 5): print(value) # 创建数字列表--实际最大输出5 numbers = list(range(1, 6)) print(numbers) # 创建偶数 even_numbers = list(range(2, 11, 2)) print(even_numbers) # 创建平方值--1~10的平方值 squares = [] for value in range(1, 11): squares.append(value**2) print(squares) # 统计计算 digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] print(min(digits)) print(max(digits)) print(sum(digits)) #列表解析 squares1 = [value**2 for value in range(1, 11)] print(squares1)
三。使用列表的一部分
切片与遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print(players[0:3]) # 起始0,终止3前元素--['charles', 'martina', 'michael'] print(players[1:4]) # 起始1,终止4前元素--['martina', 'michael', 'florence'] print(players[:4]) # 起始0,终止4前元素--['charles', 'martina', 'michael', 'florence'] print(players[2:]) # 起始2到最末尾元素--['michael', 'florence', 'eli'] print(players[-3:]) # 起始倒数第三个至最末尾一个元素--['michael', 'florence', 'eli'] # 遍历切片 print("Here are the first three plyers on my team:") for player in players[:3]: print(player.title())
四。复制列表
深拷贝与浅拷贝
my_foods = ['pizza', 'falafel', 'carrot cake'] #friend_foods = my_foods[:] # 深拷贝--两个不同列表 friend_foods = my_foods # 浅拷贝--相同一个列表,同一个引用 print("My favorite foods are:") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods) my_foods.append('cannoli') friend_foods.append('ice cream') print("My favorite foods are:") print(my_foods) print("\nMy friends favoirte foods are:") print(friend_foods)
五。元组
相当于不可变数组,只在构造时可以修改值,后的不能修改。
dimensions = (200, 50) # 只有二个元素 print(dimensions[0]) print(dimensions[1]) my_t = (3,) # 单个元素,也要加逗号 print(my_t[0]) #dimensions[0] = 300 # 运时报错,'tuple' object does not support item assignment # 遍历元组中所有元素 for dimension in dimensions: print(dimension) # 修改元组变量--构造时 dimensions = (400, 100, 50) print("\nModified dimensions:") for dimension in dimensions: print(dimension)
标签:dimensions,python,编程,列表,--,foods,print,my From: https://www.cnblogs.com/duju/p/16776150.html