Python字串操作之常忘的字串、列表、數值
字串操作
s為字串 s.isalnum() 所有字元都是數字或者字母 s.isalpha() 所有字元都是字母 s.isdigit() 所有字元都是數字 s.islower() 所有字元都是小寫 s.isupper() 所有字元都是大寫 s.istitle() 所有單詞都是首字母大寫,像標題 s.isspace() 所有字元都是空白字元 s.index(x) 返回x所在索引,如:s.index(max(s))返回第一個最大值索引
判斷是整數還是浮點數
a=123
b=123.123
>>>isinstance(a,int)
True
>>>isinstance (b,float)
True
>>>isinstance(b,int)
False
注意:在Python中,字串是不可變的,因此無法就地更改字元。
L Out[20]: 'hgfdsa' L[1] Out[21]: 'g' L[1]="k" Traceback (most recent call last): File "<ipython-input-22-dedefc94809c>", line 1, in <module> L[1]="k" TypeError: 'str' object does not support item assignment
反轉字串
L="asdfgh"
LL = list(L)
LL.reverse()
L = "".join(LL)
L
Out[19]: 'hgfdsa'
string中的index和find
find和C中的strstr函式一樣,s1.find(s2)返回s2作為s1的子字串的起始位置,若干不存在返回-1,如果s2為空返回0。 index除了不能處理不存在的情況,其他和find一樣
List操作
將兩個list合併為一個list:
list3 = list1+list2 #其中元素不能含有Notetype型別
求list、ndarray眾數
from scipy import stats mode(a, axis=0, nan_policy='propagate') Return an array of the modal (most common) value in the passed array. If there is more than one such value, only the smallest is returned. The bin-count for the modal bins is also returned. Parameters ---------- a : array_like n-dimensional array of which to find mode(s). axis : int or None, optional Axis along which to operate. Default is 0. If None, compute over the whole array `a`. nan_policy : {'propagate', 'raise', 'omit'}, optional Defines how to handle when input contains nan. 'propagate' returns nan, 'raise' throws an error, 'omit' performs the calculations ignoring nan values. Default is 'propagate'. Returns ------- mode : ndarray Array of modal values. count : ndarray Array of counts for each mode. Examples -------- a = np.array([[6, 8, 3, 0], [3, 2, 1, 7], [8, 1, 8, 4], [5, 3, 0, 5], [4, 7, 5, 9]]) from scipy import stats stats.mode(a) #預設是axis=0,即求出各列的眾數,若有出現次數相同的數字,則輸出值小的那個 (array([[3, 1, 0, 0]]), array([[1, 1, 1, 1]]))#前一個array是眾數,後一個array是對應眾數出現的次數 To get mode of whole array, specify ``axis=None``: stats.mode(a, axis=None) #axis=None為求包含矩陣中所有項的眾數 (array([3]), array([3]))
List排序
第一種:內建方法sort()
可以直接對列表進行排序
用法:
list.sort(func=None, key=None, reverse=False(or True))
對於reverse這個bool型別引數,當reverse=False時:為正向排序;當reverse=True時:為反向排序。預設為False。 執行完後會改變原來的list,如果你不需要原來的list,這種效率稍微高點 為了避免混亂,其會返回none 例如:
>>> list = [2,8,4,6,9,1,3]
>>> list.sort()
>>> list
[1, 2, 3, 4, 6, 8, 9]
第二種:內建函式sorted()
sorted()也可以對字串進行排序,字串預設按照ASCII大小來比較。 這個和第一種的差別之處在於:
sorted()不會改變原來的list,而是會返回一個新的已經排序好的list list.sort()方法僅僅被list所定義,sorted()可用於任何一個可迭代物件 用法:
sorted(list)
該函式也含有reverse這個bool型別的引數,當reverse=False時:為正向排序(從小到大);當reverse=True時:為反向排序(從大到小)。當然預設為False。 執行完後會有返回一個新排序好的list 例如:
>>> list = [2,8,4,1,5,7,3]
>>> other = sorted(list)
>>> other
[1, 2, 3, 4, 5, 7, 8]
>>> other = sorted(list,reverse=True) #sort也是如此
>>> other
[8, 7, 5, 4, 3, 2, 1]
自定義排序
import functools
L = [2,1,4,9,3,3]
def reversed_cmp(x,y):
if x>y:
return -1
if x<y:
return 1
return 0
print(sorted(L,key=functools.cmp_to_key(reversed_cmp)))
out[1]:[9, 4, 3, 3, 2, 1]
compare(x,y)傳入兩個待比較的元素 x, y,如果 x 應該排在 y 的前面,返回 -1,如果 x 應該排在 y 的後面,返回 1。如果 x 和 y 相等,返回 0。python3中需要用functools.cmp_to_key,不像python2中直接甩一個cmp函式在後面就行了。
數值操作
對數值取整的幾種方法
四捨五入: 這裡round並不總是四捨五入,在4.5的時候會得到去尾法的結果;另外round有兩個引數,第二個引數用來控制精度,預設是0(即取整);
num = 4.6
round(num)
Out[40]: 5
去尾法:
num = 4.9
int(num)
Out[36]: 4
進一法:
import math
num = 4.1
math.ceil(num)
Out[35]: 5