一、变量和list
1、定义一个变量,并赋值。
days_1 = 365 days_2 = 366 #修改变量值 number_of_days = 365 print(number_of_days) # 365 number_of_days = 366 print(number_of_days) # 366 #打印 #print print(365) # 365 print("hello") # hello
- 1.1 数值型变量有float和integer两种
- 1.2 非数值型变量通常为string
str_test = "China" int_test = 123 float_test = 122.5 print(str_test) # China
print(int_test) # 123
print(float_test) # 122.5
print(type(str_test)) # <class 'str'> print(type(int_test)) # <class 'int'> print(type(float_test)) # <class 'float'>
2、类型转换函数
str() 、 float() 、 int()
查看变量的数据类型,函数:type()
str_eight = str(8) #str_eight + 10 # 异常:TypeError: can only concatenate str (not "int") to str print(type(str_eight)) # <class 'str'> print(type(float(str_eight))) # <class 'float'> print(type(int(str_eight))) # <class 'int'> print(str_eight + 'a') # 8a print('---------') eight = 8 str_eight_two = str(eight) print(type(eight)) # <class 'int'> print(type(str_eight_two)) # <class 'str'>
二、注释
单行注释、多行注释
#单行注释 #print test # 多行注释 """ Addition:+ Subtraction:- Multiplication:* Division:/ Exponent:** """
三、数值运算
china=10 united_states=100 china_plus_10 = china + 10 us_times_100 = united_states * 100 print(china_plus_10) print(us_times_100) print(china**2) # 平方**
四、list类型变量
1、定义一个list类型变量
#LIST months = [] print(type(months)) # <class 'list'> print(months) # [] months.append("January") months.append("February") print(months) # ['January', 'February']
# 定义一个list,然后进行赋值 months = [] months.append(1) months.append("January") months.append(2) months.append("February") print(months) # [1, 'January', 2, 'February']
#定义并初始化list变量 temps = ["China",122.5,"India",124.0,"United States",134.1] print(type(temps)) # <class 'list'> print(temps) # ['China', 122.5, 'India', 124.0, 'United States', 134.1] # 获取list的某一elem元素 print(temps[1]) # 122.5
print(temps[2]) # India
2、长度函数: len()
int_months = [1,2,3,4,5,6,7,8,9,10,11,12] lenght = len(int_months) #Contains the integer value 12 print(lenght) # 12
int_months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] index = len(int_months) - 1 # 11 # 通过索引寻址 last_value = int_months[index] # 12 print(last_value) # 12 # 通过-1索引寻找队列最后一个值 print(int_months[-1]) # 12
3、list切片,分段,子集
有头无尾:指定开始索引,不指定结束索引
# 切片 months = ["Jan","Feb","Mar","Apr","May","Jun","Jul"] #指定起止索引。Values at index 2,3, but not 4. 前闭后开区间 two_four = months[2:4] print(two_four) # ['Mar', 'Apr'] # 指定开始索引,不指定结束索引 three_six = months[3:] print(three_six) # ['Apr', 'May', 'Jun', 'Jul']
无头有尾:不指定开始位置,指定结束位置
# 不指定开始位置,指定结束位置 f = open('dq_unisex_names.csv','r') # open()函数操作文件 names = f.read() # 读取文件内容 names_list = names.split(' ') # 将文件内容按换行符切分得到一个names_list first_five = names_list[:5] # 等于names_list[0:5] print(first_five) # ['Casey,176544.3281', 'Riley,154860.6652', 'Jessie,136381.8307', 'Jackie,132928.7887', 'Avery,121797.4195']
转换为二维列表
# 转换为二维列表 f = open('dq_unisex_names.csv', 'r') names = f.read() names_list = names.split(' ') nested_list = [] for line in names_list: comma_list = line.split(',') nested_list.append(comma_list) print(nested_list[0:5]) # [['Casey', '176544.3281'], ['Riley', '154860.6652'], ['Jessie', '136381.8307'], ['Jackie', '132928.7887'], ['Avery', '121797.4195']]
将数值转换为float类型,遍历实现
nested_list = [['Casey', '176544.3281'], ['Riley', '154860.6652'], ['Jessie', '136381.8307'], ['Jackie', '132928.7887'], ['Avery', '121797.4195']] numerical_list = [] for line in nested_list: name = line[0] # line是一个list count = float(line[1]) num_list = [name, count] numerical_list.append(num_list) print(numerical_list) # [['Casey', 176544.3281], ['Riley', 154860.6652], ['Jessie', 136381.8307], ['Jackie', 132928.7887], ['Avery', 121797.4195]]
list函数,append() 将子元素添加到list
从文件中读取不同日期的天气数据到list列表
# 从文件中读取不同日期的天气数据到list列表 weather_data = [] f = open("la_weather.csv",'r') data = f.read() rows = data.split(' ') # print(rows) for row in rows: split_row = row.split(',') weather_data.append(split_row) print(weather_data) # [['1', 'Sunny'], ['2', 'Sunny'], ['3', 'Sunny'], ['4', 'Sunny'], ['5', 'Sunny'], ['6', 'Rain'], ['7', 'Sunny'], ['8', 'Sunny'], ['9', 'Fog'], ['10', 'Rain']]
读出天气数据到weather列表
# 读出天气数据到weather列表 weather = [] for row in weather_data: weather.append(row[1]) print(weather) # ['Sunny', 'Sunny', 'Sunny', 'Sunny', 'Sunny', 'Rain', 'Sunny', 'Sunny', 'Fog', 'Rain'] f.close()
判断list中是否包含'cat' : 'cat' in xx
# 列表中寻找值 animals = ['cat','dog','rabbit'] for animal in animals: if animal == 'cat': print('Cat found') # in 语句,判断是否在列表 cat_found = 'cat' in animals print(cat_found)
4、读取文件,切分str得到list
4.1 文件操作函数:open("file","op")
# 读文件 f = open("test.txt","r") g = f.read() print(g) f.close()
# 写文件 f = open("test_write.txt","w") f.write("123456") f.write(" ") f.write("234567") f.close()
# 切分string得到list. str_ex = "john,plastic,joe" split_list = str_ex.split(',') print(split_list) # ['john', 'plastic', 'joe'] string_two = "How much wood can a woodchuck chuck if a woodchuck could chuck wood?" list_2 = string_two.split(' ') print(string_two) print(list_2) # ['How much wood', 'can a woodchuck chuck', 'if a woodchuck', 'could chuck wood?']
4.2 读文件内容,得到string,split()函数切分string得到list
# 读文件内容,得到string,split()函数切分string得到list f = open('test.txt','r') data = f.read() rows = data.split(' ') print(rows) # ['hello python', 'tangyudi 123', 'ML 456', 'DL 789', 'data 234']
4.3 遍历 list : for in
# loop LIST: for in cities = ["Austin", "Dallas", "Houston"] for city in cities: print(city) print("123")
Austin Dallas Houston 123
4.4 遍历list: while
# loop define: while cities = ["Austin", "Dallas", "Houston"] i = 0 while i < len(cities): print(cities[i]) i += 1
Austin Dallas Houston
4.5 range(n) 、 range(start,end,step)
rg = range(15) print(rg) for i in rg: print(i) # 设置起止和步长 rg2 = range(0,20,5) print(rg2) for i in rg2: print(i)
4.6 嵌套list的遍历
cities = [["Austin","Dallas","Houston"],['Haerbin','Shanghai','Beijing']] print(cities) for lst in cities: for city in lst: print(city)
[['Austin', 'Dallas', 'Houston'], ['Haerbin', 'Shanghai', 'Beijing']] Austin Dallas Houston Haerbin Shanghai Beijing
五、布尔类型
# Booleans cat = True dog = False print(type(cat)) # <class 'bool'> print(dog) # False
print(8 == 8) # True print(8 != 8) # False print(8 == 10) # False print(8 != 10) # True print("abc" == 'abc') # True print(["January","February"] == ["January","February"]) # True print(5.0 == 5.0) # True
true等于1,false等于0
rates = [10, 15, 20] print(rates[0] > rates[1]) # False print(rates[0] >= rates[0]) # True print(False == 0) # True print(True == 1) # True print(True == 3) # False print(True == 'a') # False
在 if 语句中,非0都为true
# If Statements sample_rate = 700 greater = (sample_rate > 5) if 'a': # if条件中,值非0则为True print(sample_rate) else: print("less then")
700
t = True f = '棒' if t: print("Now you see me") if f: print("Now you don't")
Now you see me Now you don't
六、dict 字典类型
用于存储键值对,比如,学生成绩。
定义一个字典,变量={ }。赋值新增一个元素,变量['元素名']=值。
scores = {} #定义一个scores字典 print(type(scores)) # <class 'dict'> scores["Jim"] = 80 # 新增“Jim”的成绩80 scores["Sue"] = 85 scores["Ann"] = 75 print(scores.keys()) # dict_keys(['Jim', 'Sue', 'Ann']) 获取字典的所有key print(scores.values()) # dict_values([80, 85, 75]) 获取字典的所有value print(scores) # {'Jim': 80, 'Sue': 85, 'Ann': 75} print(scores["Sue"]) # 85
# 初始化 # 方式1 students = {} students["Tom"] = 60 students["Jim"] = 70 print(students) # {'Tom': 60, 'Jim': 70} # 方式2 students = {"Tom":60, "Jim":70} print(students) # {'Tom': 60, 'Jim': 70}
字典对象的增删改查
# 增删改查 students = { "Tom": 60, "Jim": 70 } # 增 students["Ketty"] = 80 print(students) # 查 # 改 students["Tom"] = 65 print(students['Tom']) # 查 students['Tom'] += 5 # 改 print(students) # 查 {'Tom': 70, 'Jim': 70, 'Ketty': 80} # 更新 update students.update({"mogen":77, "Tom":60}) # 新增mogen,修改Tom print(students) # {'Tom': 60, 'Jim': 70, 'Ketty': 80, 'mogen': 77} # 删 del students['Tom'] # 删 print(students) # {'Jim': 70, 'Ketty': 80, 'mogen': 77} # 清空 students.clear() print(students) # {}
判断字典是否包含对象: in语句# 遍历,字典
# 判断字典中是否包含对象 students = { "Tom": 60, "Jim": 70 } print("mogen" in students) # False print('Jim' in students) # True # 遍历
# 统计单词出现次数 pantry = ["apple", "orange", "grape", "apple", "orange", "apple", "tomato", "potato", "grape"] pantry_counts = {} for item in pantry: if item in pantry_counts: pantry_counts[item] += 1 else: pantry_counts[item] = 1 print(pantry_counts) # {'apple': 3, 'orange': 2, 'grape': 2, 'tomato': 1, 'potato': 1}
七、函数
定义一个函数:无参数,无返回值
函数 # 无参数,无返回值 def firFun(): print("hello python")
无参数,有返回None
# 无参数,有返回None def numFun(): for i in range(0, 10): i return
有参数,有返回值
# 有参数,有返回值 def add(a, b): return a+b
---------------------------
print(firFun())
hello python None
print(numFun()) # None print(add(3, 5)) # 8