1、遍历列表——for循环的基本形式 magicians = ['alice', 'david', 'carolina'] for a in magicians:#for循环会读取列表中的第一个字符串,然后和a对应,再打印,然后再读取第二个字符串,再对应,再打印,进行循环 print(a) 2、for循环结合其他前面所学用法
magicians = ['alice', 'david', 'carolina']
for a in magicians:
print(a+'他的表演太棒了')#因为for循环打印的是字符串,可以用+的运算法与其他字符穿结合
3、for循环变量首字母大写,+换行
magicians = ['alice', 'david', 'carolina']
for a in magicians:
print(a.title()+'他的表演太棒了')
print('我已经迫不及待的看'+a.title()+'的下一次表演了\n')#注意换行符一定要在''里面
4、遍历加切片
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print("Here are the first three players on my team:") for player in players[:3]: print(player.title())5、创建数值列表
for value in range(1, 5): print(value) #range() 只打印数1~4。这是编程语言中常见的差一行为的结果。函数range() 让Python从指定的第一个值开始数,并在到达你指定的第二个值时停止。因为它在第二个值处停止, 所以输出不包含该值(这里为5) numbers = list(range(1, 6)) print(numbers) #打印结果即是变量列表[1, 2, 3, 4, 5] even_numbers = list(range(2, 11, 2))#加入了步长 print(even_numbers) ❶ squares = [] ❷ for value in range(1, 11): ❸ square = value ** 2 ❹ squares.append(square) ❺ print(squares) 首先,创建一个名为squares 的空列表(见❶)。接下来,使用函数range() 让Python遍历1~10 的值(见❷)。在循环中,计算当前值的平方,并将结果赋给变量square (见❸)。然后,将新计 算得到的平方值附加到列表squares 末尾(见❹)。最后,循环结束后,打印列表squares (见 ❺): squares = [value**2 for value in range(1, 11)] print(squares) #简易式,请注意,这里的for 语句末尾没有冒号,用于给表达式提供值 6、对数列的统计 >>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] >>> min(digits)#最小值 0 >>> max(digits)#最大值 9 >>> sum(digits)#总和 45 7、复制列表 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_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods my_foods.append('cannoli') friend_foods.append('ice cream') print("My favorite foods are:") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods) my_foods = ['pizza', 'falafel', 'carrot cake'] friend_foods = my_foods #如果不加切片,两个值就相等,不管后面的值怎么变,两个值都会随着变化并相等 my_foods.append('cannoli') friend_foods.append('ice cream') print("My favorite foods are:") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods) 8、元组: Python将不能修改的值称为不可变的 ,而不可变的列表被称为元组, 元组看起来很像列表,但使用圆括号而非中括号来标识。 dimensions = (200, 50) print(dimensions[0]) print(dimensions[1]) dimensions[0] = 250#这一行代码就会报错,因为你想直接改变元组中的字符 dimensions = (200, 50) print("Original dimensions:") for dimension in dimensions: print(dimension) dimensions = (400, 100)#这是可行的操作,因为你重新为dimensions进行了赋值 print("\nModified dimensions:") for dimension in dimensions: print(dimension) 标签:入门,python,编程,列表,foods,print,my,friend,dimensions From: https://www.cnblogs.com/baibaidedabaicai/p/17013887.html