数字运算很简单,不过,这里还是值得一提。

这里有3个命令,加减法、除法、小数相除。需要注意的是:整数相除,得到整数,整数与小数相除,得到高精度(小数)。
字符串是编程中经常使用到的数据类型,必须熟练掌握其用法。
1>>> s = 'hello world'
2>>> s[0]
3'h'
4>>> s[:3]
5'hel'
6>>> s + 'i am a cool boy'
7'hello worldi am a cool boy'
字符串可以当作数组使用,可以切片;
s[:3]表示,从第一个字母'h'开始到,第3个字母l结束,对应下标从0到2,得到:hel;
字符串的加法与整数加法一样,只是字符串是将两个字符串连接在一起。
1>>> s.replace('world','boy')
2'hello boy'
3>>> print "%s i'm coming"%(s)
4hello world i'm coming
replace 表示替换,把s中的'word',替换为'bool';
'%s' 表示一个字符串占位符,后面括号写对应字符串;
这里i'm有一个单引号,会与字符串定义的单引号重复,所以用了双引号;
1>>> s3 = 'hello world'
2>>> s4 = "hello world"
3>>> s5 = """hello world"""
4>>> s3
5'hello world'
6>>> s4
7'hello world'
8>>> s5
9'hello world'
10>>> s6 = '''hello world'''
11>>> s6
12'hello world'
定义字符串,可以用单引号,双引号,3引号,都行;
三个引号,通常会用来在脚本中作为注释;
列表是Python中使用最多的数据类型,列表可以有多个元素,元素可以是任何数据类型,包括它自己。
1>>> list = []
2>>> type(list)
3<type 'list'>
4>>> list.append(1)
5>>> list
6[1]
7>>> list.append(3)
8>>> list
9[1, 3]
10>>> list[:2]
11[1, 3]
12>>> list.append(5)
13>>> list[:2]
14[1, 3]
15>>> list[:]
16[1, 3, 5]
17>>> list + [7,9]
18[1, 3, 5, 7, 9]
19>>> list[-1]
205
list = [] 用来定义一个空列表;
append 向列表里面添加元素;
list[:] 取列表所有元素;
list + [7,9] 两个列表相加;
list[-1] 取倒数第一个元素,倒数第二个以此类推;
1>>> range(2,6)
2[2, 3, 4, 5]
3>>> for i in list:
4... print i
5...
61
73
85
9>>> for i in range(len(list)):
10... print list[i]
11...
121
133
145
range(m, n)从m开始到n的1为步长的序列;
for i in list: 遍历列表元素;
for i in range(lne(list)): 通过下表遍历;
1>>> s = (1,2)
2>>> s[0]
31
4>>> len(s)
52
6>>> s2 = (1,)
7>>> s3 = (1)
8>>> type(s2)
9<type 'tuple'>
10>>> type(s3)
11<type 'int'>
元组用小括号,定义,下标0开始;
len(s):同列表一样,用len求长度;
s2 = (1,) 定义一个只有一个元素的元组,要加逗号;否则就不是元组;
字典是键值对,可以装任何数据类型。
1>>> dic = dict()
2>>> type(dic)
3<type 'dict'>
4>>> dic['name'] = 'hello'
5>>> dic.get('name')
6'hello'
7>>> dic['name']
8'hello'
9>>> dic.clear()
10>>> dic
11{}
12>>> dic = {'name':'hello','age':24}
13>>> dic
14{'age': 24, 'name': 'hello'}
dic = dict() dict是关键字,用来创建空的字典,不要做变量名;
dic['name'] = 'hello' 添加元素;
dic.get('name') 取出元素;
dic['name'] 与dic.get()方法一样,二者使用一种即可;
dic = {'name':'hello','age':24} 定义一个有初始元素的字典;
1>>> dic.keys()
2['age', 'name']
3>>> dic.items()
4[('age', 24), ('name', 'hello')]
dic.keys() 获得字典的所有key;
dic.items() 获得字典所有元素(k,v),返回一个list
注意:比如dic.keys(),与dic.keys 有无括号是不一样的,一个是调用方法会有返回值,一个是没有;
字典主要用法
| 方法和函数 | 描述 |
|---|---|
| cmp(dict1, dict2) | 比较两个字典元素 |
| len(dict) | 计算字典元素个数 |
| str(dict) | 输出字典可打印的字符串表示 |
| type(variable) | 返回输入的变量类型,如果变量是字典就返回字典类型 |
| dict.clear() | 删除字典内所有元素 |
| dict.copy() | 返回一个字典的浅复制 |
| dict.values() | 以列表返回字典中的所有值 |
| popitem() | 随机返回并删除字典中的一对键和值 |
| dict.items() | 以列表返回可遍历的(键, 值) 元组数组 |
大家数学都不是体育老师交的,集合(set)与数学中集合一样,不能有重复元素,可以做交、并、差运算;

1>>> s = set([1,2,3,4,4,4])
2>>> s
3set([1, 2, 3, 4])
4>>> s.add(5)
5>>> s
6set([1, 2, 3, 4, 5])
7>>> s.remove(2)
8>>> s
9set([1, 3, 4, 5])
s = set([1,2,3,4,4,4]) 集合定义需要传入一个list;
集合通过add添加元素;
通过remove移除元素;
Python的基本数据类型还是很简单的,稍加练习就能掌握。
猜你可能喜欢





