1.一些比较容易忽略的
1.如何从列表中获取只含有一个元素的列表
只能使用切片
s = ['a', 'b', 'c', 'd']
# 取只有一个'd'的列表
s[-1]
'd'
s[-1:]
['d']
2.如何将str转化为list,怎么将list转化为str
str --->list split
list--->str join
>>> li = ['alex', 'eric', 'rain'] >>> '_'.join(li) 'alex_eric_rain' >>> type('_'.join(li))
>>> dic = {'name':'shen', 'age': 23, 'sex':'male'} >>> dic {'age': 23, 'name': 'shen', 'sex': 'male'}
<type 'str'>
3.列表运用索引改变时是作为一个对象进行改变,而列表运用切片时则是看成一个序列进行改变如下:>>> li = [1, 2, 3, 4, 5] >>> li2 = ['a', 'b', 'c'] >>> li[1] = li2 >>> li [1, ['a', 'b', 'c'], 3, 4, 5] >>> li = [1, 2, 3, 4, 5] >>> li[1:2] = li2 >>> li [1, 'a', 'b', 'c', 3, 4, 5]
2.字典
python中唯一的映射类型。映射类型的对象是哈希值(键,key)和指向的对象(值,value)是一对多的关系。2.1 字典中的增
直接创建
>>> dic = {'name':'shen', 'age': 23, 'sex':'male'}
>>> dic
{'age': 23, 'name': 'shen', 'sex': 'male'}
>>> dic1['name'] = 'shen'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'dic1' is not defined
>>> dic1 = {}
>>> dic1['name'] = 'shen'
>>> dic1
{'name': 'shen'}
>>> fdict = dict((['x','y'], [1, 2]))
>>> fdict
{'x': 'y', 1: 2}
>>> edict = {}.fromkeys(('foo', 'bar'))
>>> edict = {}.fromkeys(('foo', 'bar'),1)
>>> edict
{'foo': 1, 'bar': 1}
>>> edict = {}.fromkeys(('foo', 'bar'))
>>> edict
{'foo': None, 'bar': None}
>>> edict.setdefault('foo',1)
>>> edict
{'foo': None, 'bar': None}
>>> edict.setdefault('1234',1)
1
>>> edict
{'foo': None, 'bar': None, '1234': 1}
2.2字典的删
使用del
>>> info = {'name': 'shen','age': 23, 'sex':'male'}
>>> del info['sex']
>>> info
{'name': 'shen', 'age': 23}
使用pop(key)
>>> info.pop('fjfkjf')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'fjfkjf'
>>> info.pop('fjfkjf',None)
>>> info.pop('name')
'shen'
>>> info
{'age': 23, 'sex': 'male'}
使用clear()
>>> info
{'age': 23, 'sex': 'male'}
>>> info.clear()
>>> info
{}
2.3字典的改
dict.update(dict2)将dict2添加到dict中去
>>> info = {'name': 'shen','age': 23, 'sex':'male'}
>>> edict = {}.fromkeys(('foo', 'bar'),1)
>>> info.update(edict)
>>> info
{'name': 'shen', 'age': 23, 'sex': 'male', 'foo': 1, 'bar': 1}
>>> edict
{'foo': 1, 'bar': 1}
>>> info
{'name': 'shen', 'age': 23, 'sex': 'male', 'foo': 1, 'bar': 1}
>>> info['name'] = 'li'
>>> info
{'name': 'li', 'age': 23, 'sex': 'male', 'foo': 1, 'bar': 1}
2.4字典的查
dict.keys()
info ={'name': 'li', 'age': 23, 'sex': 'male', 'foo': 1, 'bar': 1}
for i in info.keys():
print(i)
name
age
sex
foo
bar
相同
info ={'name': 'li', 'age': 23, 'sex': 'male', 'foo': 1, 'bar': 1}
for i in info:
print(i)
dict.items()
info ={'name': 'li', 'age': 23, 'sex': 'male', 'foo': 1, 'bar': 1}
for i, j in info.items():
print(i,j)
name li
age 23
sex male
foo 1
bar 1
dict.value()
info ={'name': 'li', 'age': 23, 'sex': 'male', 'foo': 1, 'bar': 1}
for i in info.values():
print(i)
li
23
male
1
1