python-小技巧
1.空格转逗号
在我们编程时候,有时候会遇到将一个程序里边的结果放到另一个程序中,就比如这样:
[1 5 6 5 2 3 7 0 2 6 3 0 1 2 2 3 0 2 1 7 4 6 2 7 7 4 6 6 7 0 0 6 4 7 7 3 1 1 0 4 4 0 1 1 5 4 4 4 1 4 7 1 4 0 0 7 4 6 6 0 6 3 6 1 5 5 3 5 5 6 1 2 2 2 3 5 2 3 3 7 7 4 3 3 7 0 1 2 2 5 6 5 5 0 3 3 1 2 5 0]#输出 #但是我们要的列表肯定是中间逗号,是这样 [1, 5, 6, 5, 2, 3, 7, 0, 2, 6, 3, 0, 1, 2, 2, 3, 0, 2, 1, 7, 4, 6, 2, 7, 7, 4, 6, 6, 7, 0, 0, 6, 4, 7, 7, 3, 1, 1, 0, 4, 4, 0, 1, 1, 5, 4, 4, 4, 1, 4, 7, 1, 4, 0, 0, 7, 4, 6, 6, 0, 6, 3, 6, 1, 5, 5, 3, 5, 5, 6, 1, 2, 2, 2, 3, 5, 2, 3, 3, 7, 7, 4, 3, 3, 7, 0, 1, 2, 2, 5, 6, 5, 5, 0, 3, 3, 1, 2, 5, 0]
怎么办呢?一个一个改?反正我不那么做,哈哈。
方法1 isspace方法(适合1位数):
a = "1 5 6 5 2 3 7 0 2 6 3 0 1 2 2 3 \ 0 2 1 7 4 6 2 7 7 4 6 6 7 0 0 6 4 7 7 3 1 1 0 4 \ 4 0 1 1 5 4 4 4 1 4 7 1 4 0 0 7 4 6 6 0 6 3 6 1 5 \ 5 3 5 5 6 1 2 2 2 3 5 2 3 3 7 7 4 3 3 7 0 1 2 2 5 6 \ 5 5 0 3 3 1 2 5 0" b = [] for i in a: if i.isspace():#如果是空格 i = ',' else: b.append(int(i)) print(b,type(b))
方法2 print
a = "1 5 6 5 2 3 7 0 2 6 3 0 1 2 2 3 \ 0 2 1 7 4 6 2 7 7 4 6 6 7 0 0 6 4 7 7 3 1 1 0 4 \ 4 0 1 1 5 4 4 4 1 4 7 1 4 0 0 7 4 6 6 0 6 3 6 1 5 \ 5 3 5 5 6 1 2 2 2 3 5 2 3 3 7 7 4 3 3 7 0 1 2 2 5 6 \ 5 5 0 3 3 1 2 5 0" for i in a: if not i.isspace(): print(i,end = ',')
方法3 split方法(实用性更广):
b = a.split() c = [] for i in b: c.append(int(i)) print(c)
2.去掉array的[]:
#ps是一个列表,我们需要求出其中第一个大于0.9的元素的下标,但是最后结果是:[数字] #我们需要:数字 import numpy as np ps_array = np.array(ps) confidence_indexs = np.argwhere(ps_array > 0.9) print(confidence_indexs) confidence_index = confidence_indexs[0] print("数据点数应大于{}时候,置信度为90%".format( list(confidence_index)[0] ))
3.python给列表内添加多次相同元素:
weight = [0.1]*10 #添加10次0.1 #output:[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
4.设置列表步长:
#1.range()只能设置整数步长,且步长负数代表倒增加 >>> for i in range(-2,3,-2): print(i) >>> for i in range(3,-2,-2): print(i) 3 1 -1 >>> for i in range(3,-2,-0.1): print(i) Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> for i in range(3,-2,-0.1): TypeError: 'float' object cannot be interpreted as an integer #2.np.arange() 左闭右开 a = list(np.arange(-1,1,0.1,dtype = 'float32')) print(a) #output:[-1.0, -0.9, -0.79999995, -0.6999999, -0.5999999, -0.49999988, -0.39999986, -0.29999983, -0.19999981, -0.099999785, 2.3841858e-07, 0.10000026, 0.20000029, 0.3000003, 0.40000033, 0.50000036, 0.6000004, 0.7000004, 0.8000004, 0.90000045] #3.np.linspace() 包含两个端点 b = list(np.linspace(-0.5,9.5,11)) print(b) #output:[-0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
5.字典一行一个输出:
#问题:在我们字典中东西太多时候,想一行输出一个怎么办? #方法1: >>> dict1 = {1:"wo",2:"ai",3:"ni"} >>> for i in dict1: print("{}:{}".format(i,dict1[i])) 1:wo 2:ai 3:ni #方法2 >>> #items() 函数以列表返回可遍历的(键, 值) 元组数组 >>> dict1.items() dict_items([(1, 'wo'), (2, 'ai'), (3, 'ni')]) >>> for (key,value) in dict1.items(): print(key,":",value) 1 : wo 2 : ai 3 : ni >>>
6.去除字符串中的重复元素
>>> a = 'acdadsfsdgdg' >>> b = set(a) >>> b {'a', 'g', 's', 'd', 'f', 'c'} >>> c = '' >>> for i in b: c+=i >>> c 'agsdfc' >>>