list常用操作:
1、list定义:
li = ["a","b","mpilgrim","z","example"]
print (li)
print (li[1])
2、list负数索引:
li = ["a","b","mpilgrim","z","example"]
print (li[-3])
print (li[1:3])
print (li[1:-1])
print (li[0:3])
3、list增加元素:
li = ["a","b","mpilgrim","z","example"]
li.append("new") # 增加new
print (li)
li.insert(2,"new1") # 将 new 增加到第2位
print (li)
li.extend(["two","elements"])
print (li) # 增加 two, elements
4、list搜索:
li = ["a","b","mpilgrim","z","example"]
print (li.index("example"))
print (li.index("new"))
print (li.index("c")) # 没有“c”,会报错
5、list删除元素:
li = ['a','b','new','mpilgrim','z','example','new','two','elements']
li.remove("z") #删除z
print (li)
l2 = ['a','b','new','mpilgrim','example','new','two','elements']
l2.remove("new") #删除首次出现的一个值new
print (l2)
l3 = ['a','b','mpilgrim','example','new','two','elements']
l3.remove("c") #list中没有找到值,Python会引发一个异常
print (l3)
l3.pop() #pop会做两件事:删除list的最后一个元素,然后返回删除元素的值
print (l3)
6、list运算符:
li = ['a','b','mpilgrim']
li = li + ['example','new'] #增加“example”,“new”
print (li)
li += ['two']
print (li) #增加“two”
l2 = [1,2] * 3 #输出3遍[1,2]
print (l2)
7、使用join链接list成为字符串:
# join只能用于元素时字符串的list;它不进行任何的类型强制转换。链接一个存在一个或多个非字符串元素的list将引发一个异常。
params = {"server":"mpilgrim","database":"master","uid":"sa","pwd":"secret"}
print (["%s=%s" % (k,v)for k,v in params.items()])
# ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
print (";".join(["%s=%s" % (k,v)for k,v in params.items()]))
# 'server=mpilgrim;uid=sa;database=master;pwd=secret'
8、list分割字符串:
li = ['server=mpilgrim','uid=sa','database=master','pwd=secret']
s = ";".join(li)
print (s)
s1 = s.split(";") #split将字符串分割成多元素list
print (s1) #分隔符(";")被完全去掉了,它没有在返回的list中的任意元素中出现
s2 = s.split(";",1) #split接受一个可选的第二个参数,它是要分割的次数
print (s2)
9、list的映射解析:
li = [1,9,8,4]
li = [elem*2 for elem in li]
print (li)
10、dictionary中的解析:
params = {"server":"mpilgrim","database":"master","uid":"sa","pwd":"secret"}
print (params.keys()) # 取字典中的键
print (params.values()) # 取字典中的值
print (params.items()) # 将字典格式转换为列表
print ([k for k,v in params.items()])
print ([v for k,v in params.items()])
print (["%s=%s" % (k,v)for k,v in params.items()])
11、list过滤:
li = ["a","mpilgrim","foo","b","c","d","d"]
print ([elem for elem in li if len(elem) > 1])
print ([elem for elem in li if elem !="b"])
print ([elem for elem in li if li.count(elem) == 1])