目录
- 基本数据类型
- 变量和表达式
- 字符串
- 列表/list
- 判断语句
- 循环语句
- 集合/set, 元组/tuple, 字典/dictionary
- 排序
- pass 语句
1.寻求帮助
- help 查看帮助
- dir 查看对像内所有属于及方法
# 查看函数
help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
# 查看关键字
help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or
continue global pass
其他
查看python所有的modules:help(“modules”)
单看python所有的modules中包含指定字符串的modules: help(“modules yourstr”)
查看python中常见的topics: help(“topics”)
查看python标准库中的module:import os.path + help(“os.path”)
查看python内置的类型:help(“list”)
查看python类型的成员方法:help(“str.find”)
查看python内置函数:help(“open”)
查看copy模块帮助如下: help(“copy”)
2.python运算
- 加减乘除,平方,取余数
1+2
3
3-2
1
2*3
6
6/4 #python3 返回的是浮点型,python2 返回的是整数部分,舍去小数部分
1.5
4//6
0
6//4
1
4**0.5 #开方
2.0
4%3 #取余数
1
python基本数据类型、变量、运算、表达式
3.变量
基本数据类型:
* int整型
* float浮点数
* str字符串
* bool布尔型
x = 12
type(x)
int
y = -5.33
type(y)
float
a = 'note'
type(a)
str
b = True
type(b)
bool
type(open)
builtin_function_or_method
4.表达式
- python会用表达式计算并返回一个结果
statement/指令
x = 12
x = x+5
x
17
x = 12
x += 5
x
17
print(x)
17
字符串
1 2 3 4 5 6.1 8.92
my_string = 'Hello world!'
type(my_string)
str
dir(str)
['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__gt__',
'__hash__',
'__init__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']
help(str.strip)
Help on method_descriptor:
strip(...)
S.strip([chars]) -> str
Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
字符串切片
格式: [start:end:step]
- [:] 提取从开头(默认位置0)到结尾(默认位置-1)的整个字符串
- [start:] 从start 提取到结尾
- [:end] 从开头提取到end - 1
- [start:end] 从start 提取到end - 1
- [start:end:step] 从start 提取到end - 1,每step 个字符提取一个
- 左侧第一个字符的位置/偏移量为0,右侧最后一个字符的位置/偏移量为-1
my_string
'Hello world!'
len(my_string) #长度
12
my_string[4]
'o'
my_string[-6]
'w'
my_string[1:4] #左闭右开的模式
'ell'
my_string[-6:-2]
'worl'
my_string[2:] #省略的写法
'llo world!'
my_string[:5]
'Hello'
字符串函数
my_string.lower() # 小写
'hello world!'
my_string.upper() #大写
'HELLO WORLD!'
my_string.capitalize() #首字母大写
'Hello world!'
my_string.startswith('Hello')
#用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。
#如果参数 beg 和 end 指定值,则在指定范围内检查。
#str.startswith(str, beg=0,end=len(string));
#str -- 检测的字符串。
#strbeg -- 可选参数用于设置字符串检测的起始位置。
#strend -- 可选参数用于设置字符串检测的结束位置。
True
my_string.endswith('a')
False
my_string2 = ' hello ' #python的字符可以用单引号 双引号 三引号初始化
len(my_string2)
11
my_string2.strip()
'hello'
my_string3 = "我 是 中国 人"
my_string3.split(" ") #字符串切分
['我', '是', '中国', '人']
my_string3 = "我##是##中国##人"
my_string3.split("#") #字符串切分
['我', '', '是', '', '中国', '', '人']
my_string3.find("是")
3
my_string3.find("world")
-1
列表/List
序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。
names = ['HanMeimei', 'LiLei', "Honi", "Andy", "Bob", "David"]
len(names) #求长度
6
mixed = ['HanMeimei', 2, 5.11, ['LiLei',"Andy"]]
len(mixed)
4
names + mixed #组合
['HanMeimei',
'LiLei',
'Honi',
'Andy',
'Bob',
'David',
'HanMeimei',
2,
5.11,
['LiLei', 'Andy']]
'Andy' in names #判断元素是否存在于列表中
True
['hi'] * 4 #重复
['hi', 'hi', 'hi', 'hi']
for x in [1, 2, 3]: print(x) #迭代
1
2
3
列表切片
[‘HanMeimei’, 2, 5.11, [‘LiLei’,”Andy”]]
mixed[1]
2
mixed[3]
['LiLei', 'Andy']
mixed[-2]
5.11
mixed[1:]
[2, 5.11, ['LiLei', 'Andy']]
mixed[3][0]
'LiLei'
names
['HanMeimei', 'LiLei', 'Honi', 'Andy', 'Bob', 'David']
- join():连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串
" ## ".join(names)
'HanMeimei ## LiLei ## Honi ## Andy ## Bob ## David'
s = " ".join(names)
print(s)
type(s)
HanMeimei LiLei Honi Andy Bob David
str
names
['HanMeimei', 'LiLei', 'Honi', 'Andy', 'Bob', 'David']
names.append('XiaoFang')
names
['HanMeimei', 'LiLei', 'Honi', 'Andy', 'Bob', 'David', 'XiaoFang']
- list.append(obj) 在列表末尾添加新的对象
- list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
names2 = ['隔壁老王', '凤姐']
names + names2 #加法是可以拼接list
['HanMeimei',
'LiLei',
'Honi',
'Andy',
'Bob',
'David',
'XiaoFang',
'隔壁老王',
'凤姐']
names.extend(names2) #拼接list
names
['HanMeimei',
'LiLei',
'Honi',
'Andy',
'Bob',
'David',
'XiaoFang',
'隔壁老王',
'凤姐']
names.append(names2)
names
['HanMeimei',
'LiLei',
'Honi',
'Andy',
'Bob',
'David',
'XiaoFang',
'隔壁老王',
'凤姐',
['隔壁老王', '凤姐']]
- list.reverse() 反向列表中元素
names.reverse()
names
[['隔壁老王', '凤姐'],
'凤姐',
'隔壁老王',
'XiaoFang',
'David',
'Bob',
'Andy',
'Honi',
'LiLei',
'HanMeimei']
- list.insert(index, obj) 将对象插入列表
- list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
# insert pop
help(list.insert)
help(list.pop)
Help on method_descriptor:
insert(...)
L.insert(index, object) -- insert object before index
Help on method_descriptor:
pop(...)
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
流程控制
条件判断 if else
#判别一个老年人
age = 25
if age > 60:
print('yes! old man!');
elif age > 35:
print('middle age man!!');
else:
print('young man!!');
young man!!
循环
# while
# for
for name in names:
print(name)
['隔壁老王', '凤姐']
凤姐
隔壁老王
XiaoFang
David
Bob
Andy
Honi
LiLei
HanMeimei
- enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
语法:enumerate(sequence, [start=0])
参数:
sequence – 一个序列、迭代器或其他支持迭代对象。
start – 下标起始位置。
for i, name in enumerate(names):
print(i, name)
0 ['隔壁老王', '凤姐']
1 凤姐
2 隔壁老王
3 XiaoFang
4 David
5 Bob
6 Andy
7 Honi
8 LiLei
9 HanMeimei
i = 0
while i<5:
print(i)
i += 1
0
1
2
3
4
i = 0
while True:
print(i)
i += 1
if i> 5:
break
0
1
2
3
4
5
i = 0
while True:
i += 1
if i%3 ==0 :
continue
print(i)
if i>6:
break
1
2
4
5
7
列表推导式/list comprehension
names
[['隔壁老王', '凤姐'],
'凤姐',
'隔壁老王',
'XiaoFang',
'David',
'Bob',
'Andy',
'Honi',
'LiLei',
'HanMeimei']
names.pop(0)
['隔壁老王', '凤姐']
names
['凤姐',
'隔壁老王',
'XiaoFang',
'David',
'Bob',
'Andy',
'Honi',
'LiLei',
'HanMeimei']
for name in names:
print('my name is '+ name)
my name is 凤姐
my name is 隔壁老王
my name is XiaoFang
my name is David
my name is Bob
my name is Andy
my name is Honi
my name is LiLei
my name is HanMeimei
["my name is "+ name for name in names]
['my name is 凤姐',
'my name is 隔壁老王',
'my name is XiaoFang',
'my name is David',
'my name is Bob',
'my name is Andy',
'my name is Honi',
'my name is LiLei',
'my name is HanMeimei']
num_list = list(range(10))
num_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[num**2 for num in num_list if (num%2==1 and num<5)] #列表推导式
[1, 9]
集合/set
- set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
names
['凤姐',
'隔壁老王',
'XiaoFang',
'David',
'Bob',
'Andy',
'Honi',
'LiLei',
'HanMeimei']
names.append('凤姐')
names
['凤姐',
'隔壁老王',
'XiaoFang',
'David',
'Bob',
'Andy',
'Honi',
'LiLei',
'HanMeimei',
'凤姐']
set(names) # 去重复,返回新的集合
{'Andy',
'Bob',
'David',
'HanMeimei',
'Honi',
'LiLei',
'XiaoFang',
'凤姐',
'隔壁老王'}
names #原集合还在
['凤姐',
'隔壁老王',
'XiaoFang',
'David',
'Bob',
'Andy',
'Honi',
'LiLei',
'HanMeimei',
'凤姐']
- 交集、并集、差集
x = set('runoob')
y = set('google')
x,y # 重复的被删除
({'b', 'n', 'o', 'r', 'u'}, {'e', 'g', 'l', 'o'})
x & y # 交集
{'o'}
x | y # 并集
{'b', 'e', 'g', 'l', 'n', 'o', 'r', 'u'}
x - y # 差集
{'b', 'n', 'r', 'u'}
字典/dictionary
字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中
legs = {'spider':8, 'pig':4, 'duck':2} #花括号+key+value
type(legs) #返回输入的变量类型,如果变量是字典就返回字典类型。
dict
len(legs) #计算字典元素个数,即键的总数。
3
str(legs) #输出字典可打印的字符串表示
"{'spider': 8, 'duck': 2, 'pig': 4}"
legs['spider']
8
legs.keys() #以列表返回一个字典所有的键
dict_keys(['spider', 'duck', 'pig'])
legs.values() #以列表返回字典中的所有值
dict_values([8, 2, 4])
legs.items() #以列表返回可遍历的(键, 值) 元组数组
dict_items([('spider', 8), ('duck', 2), ('pig', 4)])
legs.__contains__('pig') #python 2 中是has_key()
True
'pig' in legs
True
for animal, leg_num in legs.items():
print(animal, leg_num)
spider 8
duck 2
pig 4
字典推导式
my_list = list(range(10))
my_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
{num:num**3 for num in my_list}
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512, 9: 729}
{num:num**3 for num in my_list if num%3==1}
{1: 1, 4: 64, 7: 343}
元组/tuple
Python的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
高级排序
- sorted() 函数对所有可迭代的对象进行排序操作。
sort 与 sorted 区别:
sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
语法:sorted(iterable[, cmp[, key[, reverse]]])
iterable – 可迭代对象。
cmp – 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。
key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
reverse – 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
my_list2 = [5,1,4,3]
my_list2.sort()
my_list2
[1, 3, 4, 5]
my_list2 = [5,1,4,3]
sorted(my_list2)
[1, 3, 4, 5]
my_list2
[5, 1, 4, 3]
strs = ['ccc', 'aaaaa', 'dd', 'b']
sorted(strs)
['aaaaa', 'b', 'ccc', 'dd']
sorted(strs, reverse=True)
['dd', 'ccc', 'b', 'aaaaa']
help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.
sorted(strs, key=len)
['b', 'dd', 'ccc', 'aaaaa']
tmp_strs = ['aa', 'BB', 'CC', 'zz']
sorted(tmp_strs)
['BB', 'CC', 'aa', 'zz']
sorted(tmp_strs, key=str.lower)
['aa', 'BB', 'CC', 'zz']
Python pass 语句
Python pass是空语句,是为了保持程序结构的完整性。
pass 不做任何事情,一般用做占位语句。
for letter in 'Python':
if letter == 'h':
pass
print('这是 pass 块')
print('当前字母 :', letter)
print( "Good bye!")
当前字母 : P
当前字母 : y
当前字母 : t
这是 pass 块
当前字母 : h
当前字母 : o
当前字母 : n
Good bye!