# python 列表可以加入所有类型 如列表,字典,数字,字符串等
bicycles =['trek','cannondale','redline','specialized']print(bicycles)# 访问列表元素,使用索引print(bicycles[0])# 访问最后一个元素下标-1. 以此类推print(bicycles[-1])# 修改、添加和删除元素
bicycles[1]="Hello"print(bicycles)
bicycles.append("Hallo")# 末尾添加
bicycles.insert(0,"world")# 指定位置添加del bicycles[2]# 删除指定元素
value = bicycles.pop()# 删除末尾元素
value = bicycles.pop(2)# 删除指定位置元素
bicycles.remove("world")# 列表永久性排序
bicycles.sort()# 暂时排序
sortList =sorted(bicycles)# 反转列表
bicycles.reverse()# 列表长度len(bicycles)# 操作列表# 1. 遍历操作 for
magicians =['alice','david','carolina']for magician in magicians:print(magician)# 数值列表 rangefor value inrange(1,5):#[1, 5)print(value)# 转化为数字列表list(range(1,6))# 列表切片 list[start:end] 得到[start, end)的元素 切片得到新的list
players =['charles','martina','michael','florence','eli']print(players[0:3])# players[0] players[1] players[2]print(players[:3])# from startprint(players[1:])# to end.
copyList = players[:]# 复制整个列表
Python dict
# 相关信息关联起来的Python字典 {"key": value, "key": value} key value can be any.# 字典用放在花括号{}中的一系列键—值对表示
alien_0 ={"color":"green","point":5}print(alien_0["color"])# 添加键值对
alien_0["x_position"]=1
alien_0["y_position"]=2print(alien_0)# 修改值
alien_0["color"]="yellow"print(alien_0)# 删除键值对del alien_0["color"]print(alien_0)# 遍历字典for key, value in alien_0.items():print("key: "+ key)print("value: "+str(value))for key in alien_0.keys():print("key: "+ key)for value in alien_0.values():print("value: "+str(value))
python class
# Python class# 类定义中的括号是空的,因为我们要从空白创建这个类 括号里面写的是基类classDog(object):def__init__(self, name, age):# 构造方法中,直接定义类属性# __init__()方法来创建Dog实例时,将自动传入实参self。每个与类相关联的方法# 调用都自动传递实参self,它是一个指向实例本身的引用,让实例能够访问类中的属性和方法。# self为前缀的变量都可供类中的所有方法使用,我们# 还可以通过类的任何实例来访问这些变量。self.name = name获取存储在形参name中的值,并将# 其存储到变量name中,然后该变量被关联到当前创建的实例
self.name = name
self.age = age
self.height =0# 指定初始值defsit(self):print(self.name.title()+" is now sitting")defroll_over(self):print(self.name.title()+" rolled over!")classBattery(object):def__init__(self):
self.battery =50classCar(object):def__init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading =0# 默认初始值defupdate_odometer(self, meter):
self.odometer_reading = meter
defget_descriptive_name(self):
long_name =str(self.year)+' '+ self.make +' '+ self.model
return long_name.title()classElectricCar(Car):def__init__(self):super().__init__(2023,"TS12",12)# 调用父类构造
self.battery = Battery()defupdate_odometer(self, meter):print("override.")
my_new_car = Car('audi','a4',2016)print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading =23
my_new_car.update_odometer(43)