python学习笔记(1)
操作列表
一.对列表的操作
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
(1) 设一个变量magician存储magicians列表里的值,和java不同之处在于没有具体的结束语句,将列表内的元素逐条执行直至完全遍历完。ps:注意冒号
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")
print("Thank you, everyone. That was a great magic show!")
(2) 因为python不存在{ }来界定,所以缩进就是个必要的行为,若在for语句下进行了缩进,那么缩进下的语句就是for循环内的语句,但是后面没了缩进的语句则自然为循环外的单独执行的语句。python语法中该缩进的语句不会报错,如果不该缩进的语句也进行了缩进,那便会系统报错。稍微留意下。
for value in range(1,5):
print(value)
(3) 使用函数range()打印数字,range(num1,num2),num1为起始数字(书内名为开始数),到达num2数字结束,所以并不会打印num2。
numbers = list(range(1,6))
print(numbers)
【1,2,3,4,5】
even_numbers = list(range(2,11,2))
print(even_numbers)
【2,4,6,8,10】
squares = []
for value in range(1,11):
squares.append(value**2)
print(squares)
【1,4,9,16,25,36,49....】
(4)利用list()函数将range()函数变成数字列表
dights = [1,2,3,4,5,6,7,8,9,0]
min(dights)
max(dights)
sum(dights)
(5)最小值,最大值,列表之和
squares = [value**2 for value in range(1,11)]
print(squares)
(6)for循环将1~10提供给表达式value**2。ps:注意for循环末尾没有冒号。
二. 对列表切片的介绍
players = ['charles','martina','michael','florence','eli']
print(players[0:3])
print(players[:3])
print(players[-3:])
【['charles','martina','michael']】
(7)切片,可以随意拿取列表内的元素,players[起始元素:末尾元素],从起始元素开始遍历到末尾元素结束。例子3中的-3为从后往前遍历三个。(目前没搞懂为什么搞这个和range函数循环遍历的效果一样的)
my_foods = ['pizza','falafei','carrot cake']
friend_foods = my_foods[:]
for food in my_foods[:3]:
print(food.title())
(8)使用切片进行列表的复制,复制是唯一的操作,后面是遍历的操作
三.对元祖(不可编辑的列表)的操作
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])
for dimension in dimensions:
print(dimension)
dimensions = (400,100)
(9)不能对元祖的元素进行赋值修改,只能进行重新定义,遍历与列表相似
对于书本进行的小小总结,仅限于学习使用。(推荐使用有道云笔记)