python基本数据类型——list
一、创建列表:
li = [] li = list() name_list = ['alex', 'seven', 'eric'] name_list = list(['alex', 'seven', 'eric'])
二、基本操作:
#append追加 name_list = ["zhangyanlin","suoning","nick"] name_list.append('zhang') print(name_list) #count制定字符出现几次 name_list = ["zhangyanlin","suoning","nick"] name_list.append('zhang') name_list.append('zhang') name_list.append('zhang') print(name_list.count('zhang')) #extend可扩展,批量往里加数据 name_list = ["zhangyanlin","suoning","nick"] name = ["aylin","zhang","yan","lin"] name_list.extend(name) print(name_list) #index找到字符所在的位置 name_list = ["zhangyanlin","suoning","nick"] print(name_list.index('nick')) #insert插入,往索引里面插入值 name_list = ["zhangyanlin","suoning","nick"] name_list.insert(1,"zhang") print(name_list) #pop在原列表中移除掉最后一个元素,并赋值给另一个变量 name_list = ["zhangyanlin","suoning","nick"] name = name_list.pop() print(name) #remove移除,只移除从左边找到的第一个 name_list = ["zhangyanlin","suoning","nick"] name_list.remove('nick') print(name_list) #reverse反转 name_list = ["zhangyanlin","suoning","nick"] name_list.reverse() print(name_list) #del删除其中元素,删除1到3之间的 name_list = ["zhangyanlin","suoning","nick"] del name_list[1:3] print(name_list)
#join将列表元素用指定字符串连接 name_list = ["you","are","good"] s = " ".join(name_list) print(name_list)
# you are good
list源码
三、数据类型转换
字符串转列表
元组转列表
字典转列表
dic = {'k1':'hello','k2':'morra'} l3 = list(dic) #字典在循环的时候默认只循环key print(l3) l4 = list(dic.values()) print(l4) l5 = list(dic.items()) print(l5) OUTPUT: ['k2', 'k1'] ['morra', 'hello'] [('k2', 'morra'), ('k1', 'hello')]
四、可迭代性
l = ['i', 'am', 'spark'] # 可以被for循环所迭代 for i in l: print (i) # i am spark
五、可嵌套性
li = ['字符串',('tuple','hh'),{"key1":"value1","key2":"value2"}] print(li[2]["key1"]) #输出 value1