目录
从字符串中提取数字
实数序列、复数序列
初始化矩阵后赋值
连等赋值
向上取整(ceil)
对list排序并返回排序后索引值
import re
a = 'h3110 23 cat 444.4 rabbit 11 2 dog -1 0'
b = [int(s) for s in a.split() if s.isdigit()] # 只提取非负整数
print(b) # [23, 11, 2, 0]
print('---------------------------------')
b = re.findall(r'\d+\.?\d*', a) # 提取所有数字,不包含负号,可提取小数
print(b) # ['3110', '23', '444.4', '11', '2', '1', '0']
'''
\d+ 匹配1次或者多次数字,注意这里不要写成*,因为即便是小数,小数点之前也得有一个数字
\.? 这个是匹配小数点的,可能有,也可能没有
\d* 这个是匹配小数点之后的数字的,所以是0个或者多个
'''
print('---------------------------------')
a = '3110 23 444 11 2 -1 0'
b = [int(s) for s in a.split()] # 如果str中只有整数时,可以使用该语句提取,包含负数
print(b) # [3110, 23, 444, 11, 2, -1, 0]
from numpy import *
bits = array([1, 0, 1, 1, 0, 0])
c = (1 - 2 * bits) / 2
print(c) # [-0.5 0.5 -0.5 -0.5 0.5 0.5]
c_seq = []
for i in range(0, len(c) // 2):
j = complex(c[2 * i], c[2 * i + 1])
c_seq.append(j)
print(c_seq) # [(-0.5+0.5j), (-0.5-0.5j), (0.5+0.5j)]
a = array([1, 2, 3])
b = array([2, 4, 6])
c = a + 1j * b
print(c) # [1.+2.j 2.+4.j 3.+6.j]
d = real(c)
e = imag(c)
print(d) # [1. 2. 3.]
print(e) # [2. 4. 6.]
a = [1, 2, 3]
b = zeros((3, 1)) # 新建列表后,将重新开辟一块空间
# b = a
for i in range(0, 3):
b[i] = a[i]
print(a) # [1, 2, 3]
print(b)
'''
[[1.]
[2.]
[3.]]
'''
print(id(a)) # 2250901091912
print(id(b)) # 2250860299408
print(id(a[0])) # 140706888589712
print(id(b[0])) # 2250901120544
'''
对比地址可知,开辟新空间后的赋值,不是使两个标签指向相同的元素
'''
a = b = c = 0
print(id(a)) # 140706888589680
print(id(b)) # 140706888589680
print(id(c)) # 140706888589680
b = 1
c = 2
print(a) # 0
print(b) # 1
print(c) # 2
print(id(a)) # 140706888589680
print(id(b)) # 140706888589712
print(id(c)) # 140706888589744
from math import *
a = 3
c = 3.5
print(ceil(a))
print(ceil(c))
import operator
a = [9, 5, 2, 7]
b = dict(zip(range(len(a)), a)) # 把list转化为dict,key为索引值
c = sorted(b.items(), key=operator.itemgetter(1), reverse=True)
'''
sorted为从小到大排序
reverse缺省值为False,True表示进行反序,即对b从大到小排序
1表示按key值(a中元素)排序,若为0,则按key排序
'''
print(a) # [9, 5, 2, 7]
print(b) # {0: 9, 1: 5, 2: 2, 3: 7}
print(c) # [(0, 9), (3, 7), (1, 5), (2, 2)]
c = sorted(b.items(), key=operator.itemgetter(0), reverse=True)
print(c) # [(3, 7), (2, 2), (1, 5), (0, 9)]