python学习

数字

python 支持四种不同类型的数值,int、long integers、floating point real values、complex numbers

x = 1
print(int(x))
print(float(x))
print(complex(x))
print(str(x))
print(repr(x))
1
1.0
(1+0j)
1
1

python很多数学运算函数在math模块和cmath模块中

import math
print(dir(math))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
import cmath
print(dir(cmath))
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']

python 的随机数函数

from random import *
sqe = [1,2,3,4,5,6,7,8,9,10]
print(choice(sqe))
print(randrange(0,100,10))# [0,100)中以步数为10随机取数
4
20
print(random())# [0,1]范围内生成随机实数
0.13751930311626015
shuffle(sqe)
sqe
[1, 5, 10, 7, 9, 2, 6, 3, 4, 8]
print(uniform(1,2))
1.710793429870846

字符串

python不支持单字符类型,每个都是字符串

s  = 'apple'
print(s[:]) ## 默认情况下左右都是完整的字符串
apple
print(s[0:4])
print(s[2:3])## 取左闭右开的区间
appl
p
print(s[1:])#默认取到最后
print(s[:4])
pple
appl
print(s[:-1])#注意因为是左闭右开,无法取到最后一个
appl
print(s[::2])#每两个字符取一个
ape
print(s[::-1])#翻转
elppa

python 转义字符,在字符串中使用特殊字符时,要用\转义字符,字符串前r认为字符串中无转移字符

s = "\\"
print(s)
s = r"\\"
print(s)
\
\\
a = 'hello'
b = 'python'
print(a + b)
print(a * 3)
print('h' in a)
hellopython
hellohellohello
True

字符串有很多内置函数,其中比较常用有

a = 'hello python'
print(a.count('heo'))
print(a.endswith('on'))
print(a.find('o',0,5))#注意是左闭右开
print(a.replace('hello','你好'))
print(a.split(" "))
0
True
4
你好 python
['hello', 'python']

列表

list1 = list()
print(list1)
list1.append("123")
list1.append("abc")
print(list1)
del list1[1]
print(list1)
[]
['123', 'abc']
['123']

列表中能用一些函数和方法

list1 = [1,2,3]
list2 = [4,5,6]
print(list1 < list2)
True

如果比较的元素是同类型的,则比较其值,返回结果。

如果两个元素不是同一种类型,则检查它们是否是数字。

  • 如果是数字,执行必要的数字强制类型转换,然后比较。
  • 如果有一方的元素是数字,则另一方的元素"大"(数字是"最小的")
  • 否则,通过类型名字的字母顺序进行比较。

如果有一个列表首先到达末尾,则另一个长一点的列表"大"。

print(len(list1))
print(max(list1))
print(list((1,2)))
3
3
[1, 2]
print(list1 + list2)
[1, 2, 3, 4, 5, 6]
list1 = [1, 2, 3]
print(list1.index(3))
list1.insert(-1, 4)
print(list1)
list1.pop(-1)
print(list1)
list1.remove(1)
print(list1)
2
[1, 2, 4, 3]
[1, 2, 4]
[2, 4]
list2 = [1,-1,-3,2,4]
list2.sort(key = abs)
print(list2)
[1, -1, 2, -3, 4]

元组

元组与列表类似,但是元组中的元素不能修改

字典

字典是存储键值对的容器

dict = {'name':'rob', 'likes':123,'url': 'www.wqy.com'}
print(dict['likes'])
del dict['name']
print(dict)
123
{'likes': 123, 'url': 'www.wqy.com'}
dict = {'name':'rob', 'likes':123,'url': 'www.wqy.com'}
dict1= dict.copy()
dict.clear()
print(dict)
print(dict1)
t = dict1.items()
t1 = dict1.keys()
t2 = dict1.values()
for i, j in t:
    print(i ,':', j)
print('--------')
for val in t2:
    print(val)
{}
{'name': 'rob', 'likes': 123, 'url': 'www.wqy.com'}
name : rob
likes : 123
url : www.wqy.com
--------
rob
123
www.wqy.com

集合

集合是一个无序的不重复元素序列
使用{}或者set()创建

a = set('abracadabra')
print(a)
b = set('alacazam')
print(b)
print(a - b)
{'a', 'b', 'r', 'c', 'd'}
{'a', 'm', 'z', 'c', 'l'}
{'d', 'r', 'b'}
a.update('z')
print(a)
a.discard('a')
print(a)
a.pop()
print(a)
{'b', 'z', 'r', 'c', 'd'}
{'b', 'z', 'r', 'c', 'd'}
{'z', 'r', 'c', 'd'}

高级特性

  • 列表生成式
  • 生成式
  • 迭代器
list1 = [x * x for x in range(1,11) if x % 2 == 0]
print(list1)
[4, 16, 36, 64, 100]
list2 = [x if x % 2 == 0 else -x for x in range(1,11)]
print(list2)
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [x.lower() for x in L1 if type(x) == type('s')]
print(L2)
['hello', 'world', 'apple']

生成器是一种不太占内存,在不断循环中计算列表的元素的机制

g = (x*x for x in range(1,11))
print(g)

list1 = list()
for n in g:
    list1.append(n)
print(list1)
for i in g:## 用过就没了
    print(i)
<generator object <genexpr> at 0x000001A5C34FE9E0>
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
def fib(n):
    i, a, b = 0, 1, 1
    while i < n:
        yield a ##遇到yield停止并返回,下次next从此继续
        a, b = b, a + b
        i = i + 1
    return 'done'
g = fib(6)
for i in g:
    print(i)
1
1
2
3
5
8

函数式编程

python中有map()reduce()函数,map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。

it = map(abs,[1,-1,-5,6,2,-3])
list1 = list()
for i in it:
    list1.append(i)
print(list1)
[1, 1, 5, 6, 2, 3]

reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算

from functools import reduce
list1 = [i for i in range(1,101)]
print(reduce(lambda x,y : x+y,list1))
5050

python中内建有filter()函数用于过滤序列,和map()类似,filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。

list1 = list(range(1,11))
g = filter(lambda x: x % 2 == 0, list1)
print(list(g))
[2, 4, 6, 8, 10]
def count():
    fs = []
    for i in range(1, 4):
        def f():
             return i*i
        fs.append(f)
    return fs
f1,f2,f3 = count()
print(f1())
print(f2())
9
9

偏函数可以固定某个函数的一个参数,返回写的函数

import functools
int2 = functools.partial(int, base=2)
print(int2('101010'))
42
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值