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源码

 

三、数据类型转换

字符串转列表

复制代码
s = "你好morra"
li = list(s)
print(li)

OUTPUT:
['你', '好', 'm', 'o', 'r', 'r', 'a']
复制代码

元组转列表

复制代码
tu = ("你好","alex")
li = list(tu)
print(li)

OUTPUT:
['你好', 'alex']
复制代码

字典转列表

复制代码
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

 

posted @ 2017-06-02 23:51  叶常绿  阅读(155)  评论(0编辑  收藏  举报
友情链接:回力鞋专卖店 | 中老年女装 | 武汉英语培训机构 | 经典电影 | 托福考试费用