1.字符串
<string>.strip() 去掉两边空格及去指定字符
<string>.split() 按指定字符分隔字符串为数组
<string>.isdigit()判断是否为数字类型
字符串操作集:
tt=322
tem='%d' %tt
tem即为tt转换成的字符串
字符串长度len(tt)
import string
f2 = string.atof(a1)
列表转字符串:
dst = '.'.join(list1)
2.元组--不可更改的数据序列
被用圆括号包围()
3.列表--
[]
>>> living_room=("rug","chair")
>>> living_room
('rug', 'chair')
>>> apartment=[]
>>> apartment.append(living_room)
>>> apartment
[('rug', 'chair')]
>>> apartment.extend(living_room)
>>> apartment
[('rug', 'chair'), 'rug', 'chair']
apartment.extend(living_room)将living_room中的每个元素都插入到调用它的列表中
stop = [line.strip().decode('utf-8', 'ignore') for line in open('/home/xdj/chstop.txt').readlines()]
outStr = ''
for word in wordList:#
if not word in stop: #不在列表中
outStr += word
outStr += ' '
fout.write(outStr.strip().encode('utf-8')) #将分词好的结果写入到输出文件
二维列表/数组
2d_list = [[0 for col in range(cols)] for row in range(rows)]
其中cols, rows变量替换为你需要的数值即可
4.字典--
{}
- dic为比较函数,value 为排序的对象(这里指键或键值),
- reverse:注明升序还是降序,True--降序,False--升序(默认)
>>> a = {1:0.12, 2:0.012, 0:0.22}
>>> a
{0: 0.22, 1: 0.12, 2: 0.012}
>>> a = sorted(a.iteritems(), key= lambda asd:asd[1],reverse = False)
>>> a
[(2, 0.012), (1, 0.12), (0, 0.22)] #变成了list , 数据结构转变
>>> a = sorted(a.iteritems(), key= lambda asd:asd[0])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'iteritems'
>>> a[1]
(1, 0.12)
>>> a[0]
(2, 0.012)
>>> a[2]
(0, 0.22)
>>> a[0][0]
2
增加元素
>>> a = {1:0.123}
>>> a[2]=0.325 #方式一
>>> a
{1: 0.123, 2: 0.325}
>>> a.setdefault(3,0.25) #方式二
0.25
>>> a
{1: 0.123, 2: 0.325, 3: 0.25}
>>> a[2]=0.999 区别:在原来基础上修改
>>> a
{1: 0.123, 2: 0.999, 3: 0.25}
>>> a.setdefault(2,0.111) 保持原来键-值对
0.999
>>> a
{1: 0.123, 2: 0.999, 3: 0.25}
>>>
5.集合set--互不相同的值