列表

什么是列表

1)所谓列表,我们可以简单的把它理解为按照索引存放各种集合,在列表中,每个位置代表⼀个元素。

2)在Python中, 列表的对象⽅法是list类提供的,列表是有序的。

列表的特点

列表的特点具体如下:

a. 可存放多个值(指可存放不同的数据类型);(例如:list=[3,"a",1.0,True])

b. 按照从左到右的顺序定义列表元素,下标从0开始顺序访问;

c. 列表是有序的;

d. 列表也是可变化的,也就是说可以根据列表的索引位置来修改列表的值。

列表的常见方法

增加

append:添加的元素默认在列表的最后一位;

insert:可以指定添加元素的位置。

1 list1=["Java","Python","Go"]
2 list1.append("Net")
3 print(list1)
4 list1.insert(0,"C")
5 print(list1)

运行结果如下:

删除

pop:返回删除的对象(默认最后一位)

remove:指定删除的对象

1 list1=["Java","Python","Go"]
2 print(list1)
3 print(list1.pop())
4 list1.remove("Python")
5 print(list1)

运行结果如下:

清空:clear()

1 list1=["Java","Python","Go"]
2 list1.clear()
3 print(list1)

运行结果如下:

获取列表对象的长度:len()

1 list1=["Java","Python","Go"]
2 print(len(list1))

运行结果如下:

获取对象的索引:index()

1 list1=["Java","Python","Go"]
2 print(list1.index("Go"))

运行结果如下:

获取对象的个数:count()

1 list1=["Java","Python","Go"]
2 print(list.count("Go"))

运行结果如下:

复制对象:copy()

1 list1=["Java","Python","Go"]
2 list2=list1.copy()
3 print(list2)

运行结果如下:

extend():追加

1 list1=["Java","Python","Go"]
2 list3=[1,2,3]
3 list1.extend(list3)
4 print(list1)
5 print(list3)

运行结果如下:

列表的修改->找到值并重新赋值

1 list1=["Java","Python","Go"]
2 list1[0]="Java language"
3 list1[1]="Python language"
4 list1[2]="Go language"
5 print(list1)

运行结果如下:

反转:reverse()

list3=[0,1,2,3,4,5,6,7,8,9] 
list3.reverse()
print(list3)

运行结果如下:

排序:sort()(针对相同的数据类型,从小到大排序)

list1=[12,62,23,56,75,36,87,38,23]
list1.sort(reverse=True)
print(list1)

运行结果如下:

索引

1 list1=["Java","Python","Go","C"]
2 for index,item in enumerate(list1):
3     print(index,item)
4 if index==3 and item=="C":
5     print("继续加油!")

运行结果如下:

切片

1 list1=[1,2,3,4,5,6,7,8,9]
2 print(list1[0:3])   #输出从第一个数到第三个数
3 print(list1[-1])    #输出倒数第一个位数
4 print(list1[-2])    #输出倒数第二个位数
5 print(list1[6])     #输出第索引号为6的数
6 print(list1[-3])    #输出倒数第三个数

运行结果如下:

列表推导式

1 list4=[x for x in range(10) if x >2]
2 print(list4)
3 #列表推导式的理解:
4 list5=[]
5 for item in range(10):
6     if item>2:
7         list5.append(item)
8 print(list5)

运行结果如下:

zip ()

1 list6=list()
2 for item in zip(list1,list2):
3     list6.append(item)
4 print(list6)

运行结果如下:

定义列表的两种方式:list6=[]、list6=list()

set()

怎么找出两张excel表中的不同数据?

1)把Excel表中的数据分别保存在两个列表中;

2)然后对这两个列表使用set集合的对称差集方法就可以找出两张excel表中的不同数据。

1 list1=["go","java","python","c"]
2 list2=["net","a","c","java","go"]
3 print(set(list1)&set(list2))  #取出两个对象中相同的数据(交集)
4 print(set(list1)|set(list2))  #并集(列表1和列表2共同拥有的元素)
5 print(set(list1)-set(list2))  #差集(列表1中有而列表2中没有的元素)
6 print(set(list1)^set(list2)) #对称差集(列表1或列表2 中,但不会同时出现在二者中)

运行结果如下:

元组

列表与元组的区别

a.列表是可变的,可以添加新的元素,也可以任意删除元素;

b.元组是不可变的(结构不可变)

注意事项

当元组里边只有一个元组的时候,记得加逗号。

元组的操作

获取值

1 tuple1=("Java","Python","Go",[1,2,3])
2 print(tuple1[1])

运行结果如下:

修改值

1 tuple1=("Java","Python","Go",[1,2,3])
2 tuple1[3][0]="First"
3 print(tuple1)
4 print(tuple1.count("Python"))
5 print(tuple1.index("Python"))
6 tuple1="Go,"
7 print(type(tuple))

运行结果如下:

列表、元组实战

1)data=[

    ("wuya","99"),

    ("zhangsan","88"),

    ("lisi","77")

    ("wangwu","66")]

a.输出所有成绩;

b.获取成绩的最高分、最低分、平均分、并对成绩进行排序

解答1:

 1 data=[
 2     ("wuya","99"),
 3     ("zhangsan","88"),
 4     ("lisi","77"),
 5     ("wangwu","66")]
 6 
 7 score=[]
 8 for item in data:
 9     score.append(int(item[1]))
10 print(score)
11 print("最高分:",max(score))
12 print("最低分:",min(score))
13 print("平均分:",sum(score)/len(score))
14 score.sort()
15 print("分数排序:",score)

运行结果如下:

解答2:

 1 data=[
 2     ("wuya","99"),
 3     ("zhangsan","88"),
 4     ("lisi","77"),
 5     ("wangwu","66")]
 6 
 7 score=[int(x[1]) for x in data]
 8 print(score)
 9 print("最高分:",max(score))
10 print("最低分:",min(score))
11 print("平均分:",sum(score)/len(score))
12 score.sort()#sort()函数只能先排序后打印
13 print("分数排序:",score)

运行结果如下:

2)有列表data1=["Go","阿狸","腾讯","百度","字节跳动"],请获取公司数据。

解答:

1 data1=["Go","阿狸","腾讯","百度","字节跳动"]
2 language,*company=data1   # *表示只获取此字段之后的所有值
3 
4 print(language)

运行结果如下:

3)有列表data2=[["Go",["Java"]]],只输出Java。

解答:

data2=[["Go",["Java"]]]
print(data2[0][1][0])

运行结果如下:

4)有列表lists=["正常双休",

      "带薪年假",

      "五险一金"]

以字符形式输出此列表内容。

解答:

lists=["正常双休","带薪年假","五险一金"]
print(",".join(lists))

运行结果如下:

字典

字典的特点

1)字典是无序的

2)字典是通过key-value键值对的数据形式来存储数据的。

字典的操作

获取value的值

1 dict1={"name":"cch","age":"18"}
2 #方式1:
3 print(dict1.get("age"))
4 #方式2:
5 print(dict1["name"])

运行结果如下:

增加字典

1 dict1={"name":"cch","age":18}
2 dict1["address"]="宝鸡"
3 print(dict1)

运行结果如下:

修改字典的值

1 dict2={"name":"cch","age":18,"address":"宝鸡"}
2 dict2["address"]="西安"
3 print(dict2)

运行结果如下:

删除字典的值

1 dict3={"name":"cch","age":18,"address":"宝鸡"}
2 del dict3["address"]
3 print(dict3)

运行结果如下:

获取所有的key值

1 dict4={"name":"cch","age":18,"address":"宝鸡"}
2 for key in dict4.keys():
3     print(key)

运行结果如下:

获取所有的value值

1 dict4={"name":"cch","age":18,"address":"宝鸡"}
2 for value in dict4.values():
3     print(value)

运行结果如下:

字典循环

1 dict4={"name":"cch","age":18,"address":"陕西宝鸡"}
2 for key,value in dict4.items():
3     print(key,":",value)

运行结果如下:

追加:update()

1 dict4={"name":"cch","age":18,"address":"陕西宝鸡"}
2 dict5={"language":"Python"}
3 dict4.update(dict5)
4 print(dict4)

运行结果如下:

复杂的字典

dict4={“name”:“cch”,"age":"18","adress":"陕西宝鸡","data":[{"english":90,"math":100}]}

输出math的值

1 dict4={"name":"cch","age":18,"address":"陕西宝鸡","data":[{"english":90,"math":100}]}
2 print(dict4["data"][0]["math"])

运行结果如下:

字典的排序

思路

1、字典的排序使用的是关键字sorted()

2、dict.items()针对字典进行循环输出key和value;

3、在sorted内部把Key和value分别存储在不同的列表中;

4、然后根据 key=lambda item:item[0]来进行排序处理:

  a.根据索引来进行排序

  b.然后把排序的结果信息进行拼接

5、强制的转为字典数据类型。

按key排序

1 dict6={"name":"cch","age":18,"sex":"","address":"陕西宝鸡"}
2 data=dict(sorted(dict6.items(),key=lambda item:item[0]))
3 print(data)

运行结果如下:

按value 排序

1 dict6={"name":"cch","age":"18","sex":"","address":"陕西宝鸡"}
2 data1=dict(sorted(dict6.items(),key=lambda item:item[1]))
3 print(data1)

运行结果如下:

实现字典的有序

1 from collections import OrderedDict
2 data3=OrderedDict()
3 data3["age"]=18
4 data3["address"]="宝鸡"
5 data3["name"]="cch"
6 print(dict(data3))

运行结果如下:

数据类型之间的转换

列表与字符串

字符串转列表

1 str ="Java,Python,Go"
2 str_list=str.split(",")
3 print(str_list)
4 print(type(str_list))

运行结果如下:

列表转字符串

1 str ="Java,Python,Go"
2 str_list=str.split(",")
3 list_str=",".join(str_list)
4 print(list_str)
5 print(type(list_str))

运行结果如下:

列表与元组

元组转列表

1 tuple1=("Go",)
2 tuple_list=list(tuple1)
3 print(tuple_list)
4 print(type(tuple_list))

运行结果如下:

列表转元组

1 tuple1=("Go",)
2 tuple_list=list(tuple1)
3 list_tuple=tuple(tuple_list)
4 print(list_tuple)
5 print(type(list_tuple))

运行结果如下:

列表与字典

列表转字典

1 list1=["Java","Python","Go"]
2 list_dict=dict(enumerate(list1))
3 print(list_dict)
4 print(type(list_dict))

运行结果如下:

字典转列表

1 list1=["Java","Python","Go"]
2 list_dict=dict(enumerate(list1))
3 dict_list=list(list_dict.items())
4 print(dict_list)
5 print(type(dict_list))

运行结果如下:

字符串与字典

字符串转为字典

1 str1="Java,Python,Go"
2 str2=list(str1.split())
3 str_dict=dict(enumerate(str2))
4 print(str_dict)
5 print(type(str_dict))

运行结果如下:

字典转为字符串

1 str1="Java,Python,Go"
2 str2=list(str1.split())
3 str_dict=dict(enumerate(str2))
4 dict_list=list(str_dict.items())
5 list_str=",".join(str2)
6 print(list_str)
7 print(type(list_str))

运行结果如下:

字典的实战题

 1 student_score={
 2     "":100,
 3     "":48,
 4     "":75,
 5     "":89,
 6     "":62}
 7 
 8 minScore=min(zip(student_score.values(),student_score.keys()))
 9 print(minScore)
10 maxScore=max(zip(student_score.values(),student_score.keys()))
11 print(maxScore)

运行结果如下:

实战练习题:

1、给一组城市相关的数据,提取相应的城市名。

解答:city=[]

for item  in data["ZpData"]["hotCityList"]:

  print(data["name"])

  city.append(item["name"])

print(city)

2、字符串与字典的转换

解答:

1)字符串转为字典

1 str1="Java,Python,Go"
2 str2=list(str1.split())
3 str_dict=dict(emnerate(str2))
4 print(str_dict)
5 print(type(str_dict))

运行结果如下图:

2)字典转为字符串

1 str1="Java,Python,Go"
2 str2=list(str1.split())
3 str_dict=dict(enumerate(str2))
4 dict_list=list(str_dict.items())
5 list_str=",".join(str2)
6 print(list_str)
7 print(type(list_str))

运行结果如下图:

3、输出c

解答:

1 lists=['language',['go','python',['java','net',['c']]]]
2 print(lists[1][2][2][0])

运行解果如下:

4、输出分数的最高,最小,平均dict1={'name':'wuya',"score":[{"english":90},{"math":90},{"wuli":90}]

 解答1:

 1 dict1={'name':'wuya',"score":[
 2     {"score":90},
 3     {'score':88},
 4     {'score':60}]}
 5 Score=[]
 6 for item in dict1["score"]:
 7     Score.append(item["score"])
 8 print(Score)
 9 print("最大:",max(Score))
10 print("最小:",min(Score))
11 print("平均:",sum(Score)/len(Score))

运行结果如下:

解答2:

 1 dict1={'name':'wuya',"score":[
 2     {"score":90},
 3     {'score':88},
 4     {'score':60}]}
 5 lists=[]
 6 for item in dict1["score"]:
 7     for key,value in item.items():
 8 
 9         lists.append(item["score"])
10 print(lists)
11 print("最高分:",max(lists))
12 print("最低分:",min(lists))
13 print("平均分:",sum(lists)/len(lists))

运行结果如下:

5、输出唐山

解答:datas=["go",["name":"list","age":"18","adress":["xian","唐山"]]]

1 datas=["go",{"name":'lisi',"age":18,'address':["xian",'唐山']}]
2 print(datas[1]["address"][1])

运行结果如下:

6、按照key和value进行排序

解答:dict2={"name":"cch","sex":"girl","job":"testDev","salary":109.09}

1)按照key排序

1 dict2={"name":"cch","sex":"girl","job":"testDev","salary":109.09}
2 dict3=dict(sorted(dict2.items(),key=lambda item:item[0]))
3 print(dict3)

运行结果如下:

2)按照value排序

1 dict2={"name":"cch","sex":"girl","job":"testDev","salary":"109.09"}
2 dict3=dict(sorted(dict2.items(),key=lambda item:item[1]))
3 print(dict3)

运行结果如下:

7、根据数据,输出成城市名称

解:

1 data4={"code":0,"message":"Success","zpData":[{"name":"全国","code":100010000,"url":"/?city=100010000"},{"name":"北京","code":101010100,"url":"/beijing/"},{"name":"上海","code":101020100,"url":"/shanghai/"},{"name":"广州","code":101280100,"url":"/guangzhou/"},{"name":"深圳","code":101280600,"url":"/shenzhen/"},{"name":"杭州","code":101210100,"url":"/hangzhou/"},{"name":"天津","code":101030100,"url":"/tianjin/"},{"name":"西安","code":101110100,"url":"/xian/"},{"name":"苏州","code":101190400,"url":"/suzhou/"},{"name":"武汉","code":101200100,"url":"/wuhan/"},{"name":"厦门","code":101230200,"url":"/xiamen/"},{"name":"长沙","code":101250100,"url":"/changsha/"},{"name":"成都","code":101270100,"url":"/chengdu/"},{"name":"郑州","code":101180100,"url":"/zhengzhou/"},{"name":"重庆","code":101040100,"url":"/chongqing/"},{"name":"佛山","code":101280800,"url":"/foshan/"},{"name":"合肥","code":101220100,"url":"/hefei/"},{"name":"济南","code":101120100,"url":"/jinan/"},{"name":"青岛","code":101120200,"url":"/qingdao/"},{"name":"南京","code":101190100,"url":"/nanjing/"},{"name":"东莞","code":101281600,"url":"/dongguan/"},{"name":"昆明","code":101290100,"url":"/kunming/"},{"name":"南昌","code":101240100,"url":"/nanchang/"},{"name":"石家庄","code":101090100,"url":"/shijiazhuang/"},{"name":"宁波","code":101210400,"url":"/ningbo/"},{"name":"福州","code":101230100,"url":"/fuzhou/"}]}
2 city=[]
3 for item in data4["zpData"]:
4     city.append(item["name"])
5 print(city)

运行结果如下: