l = [‘1,1.2,‘a‘‘] #l=list([1,1.2,‘a‘])
l = [111,‘egon‘,‘hello‘]
l.append(333)
print(l)
[111, ‘egon‘, ‘hello‘, 333]
l = [111,‘egon‘,‘hello‘]
l.insert(0,‘alex‘)
print(l)
[‘alex‘, 111, ‘egon‘, ‘hello‘]
a = [1,2,3]
l = [111,‘egon‘,‘hello‘]
l.extend(a)
print(l)
[111, ‘egon‘, ‘hello‘, 1, 2, 3]
l = [111,‘egon‘,‘hello‘]
del l[1]
print(l)
[111, ‘hello‘]
l = [111,‘egon‘,‘hello‘]
res = l.pop(1)
print(res)
egon
l = [111,‘egon‘,‘hello‘]
res = l.remove(‘egon‘)
print(res)
None
l = [1,‘aaa‘,‘bbb‘,‘aaa‘,‘aaa‘]
1 l.count()
print(l.count(‘aaa‘))
2 l.index()
print(l.index(‘aaa‘))
3 l.clear()清空列表
print(l.clear(‘aaa‘))
4 l.sort() 默认从小到大排序,升序。只可同类型元素比较啊哦,如数字和数字比较,字母和字母比较
l.sort(reverse = True)从大到小排序,降序
1: 3
2: 1
3:[]
t = (10,)
print(type(t))
<class ‘tuple‘>
index:检测不存在元组里的元素会报错
t=(2,3,111,111,111,111)
print(t.index(111))
print(t.index(1111111111))
print(t.count(111))
2
Traceback (most recent call last):
File "D:/JetBrains/New Test/New 1/3.10.py", line 240, in <module>
print(t.index(1111111111))
ValueError: tuple.index(x): x not in tupl
d={‘k1‘:111,(1,2,3):222} # d=dict(...)
print(d[‘k1‘])
print(d[(1,2,3)])
print(type(d))
111
222
<class ‘dict‘>
d{} 默认定义出来的是空字典
d=dict(x=1,y=2,z=3)
print(d,type(d))
{‘x‘: 1, ‘y‘: 2, ‘z‘: 3} <class ‘dict‘>
dic = {‘age‘: 18, ‘hobbies‘: [‘play game‘, ‘basketball‘], ‘name‘: ‘xxx‘}
print(dic.keys()) #获取所有keys()
print(dic.values()) #获取所有的value
print(dic.items()) #获取所有的键值对
dict_keys([‘age‘, ‘hobbies‘, ‘name‘])
dict_values([18, [‘play game‘, ‘basketball‘], ‘xxx‘])
dict_items([(‘age‘, 18), (‘hobbies‘, [‘play game‘, ‘basketball‘]), (‘name‘, ‘xxx‘)])
dic 默认遍历的是字典的key
dic.keys :遍历的是字典的key
dic.values:遍历的是字典的value
dic.items:遍历的是字典的key和value
a、xxx.get( #key)
key存在,则获取对应的value的值
不存在,则返回None,不报错
xxx.get(key,666) key不存在的时候,可设置默认返回的值
ps:字典取值建议使用get
b、xxx.pop()
删除指定key对应的值,并返回
c、popitem()
随即删除一组键值,并将随即删除的键值放到元组内返回
dic= {‘k1‘:‘jason‘,‘k2‘:‘Tony‘,‘k3‘:‘JY‘}
item = dic.popitem() # 随机删除一组键值对,并将删除的键值放到元组内返回
print(dic)
{‘k3‘: ‘JY‘, ‘k2‘: ‘Tony‘}
print(item)
(‘k1‘, ‘jason‘)
d、update()
用于字典更新,有则修改,没有则添加
e、fromkeys()
dic = dict.fromkeys([‘k1‘,‘k2‘,‘k3‘],[])
print(dic)
{‘k1‘: [], ‘k2‘: [], ‘k3‘: []}
f、setdefault()
key不存在则新增键值对,并将新增的value返回
dic={‘k1‘:111,‘k2‘:222}
res=dic.setdefault(‘k3‘,333)
print(res)
333
print(dic) # 字典中新增了键值对
{‘k1‘: 111, ‘k3‘: 333, ‘k2‘: 222}
key存在则不做任何修改,并返回已存在key对应的value值
dic={‘k1‘:111,‘k2‘:222}
res=dic.setdefault(‘k1‘,666)
print(res)
111
print(dic) # 字典不变
{‘k1‘: 111, ‘k2‘: 222}
的value
原文:https://www.cnblogs.com/NevMore/p/12465098.html