Python之數組

前言

因爲Python的數據結構較爲靈活,長期使用java編程的我,有時候可能就搞混淆了。此時,記錄一些騷操做。java

不定長二維數組

array = [4,65,46,57,5];

array2d = [[]]*len(pages); #建立二維數組 [[], [], [], [],...,[]]
# print(array2d [0][0])
print(array2d )
for i in range(len(array2d )):
    array2d [i]=[];
    pass;

array2d[0].append(46);
array2d[2].append(35);
array2d[1].extend([46,68,23,24]);

print(array2d )

排序

  • <數組,字典>的排序 [ {...},...,{...} ]
array = [
                {'key':587,'value':'jack'},
                {'key':364,'value':'jame'},
                {'key':476,'value':'jane'},
                {'key':355,'value':'johnny'}
            ]

array = sorted(array , key=lambda x:x['value']) 
array .sort(array p,q: cmp(p['value'], q['value']))
  • 排序後基於索引輸出
    • 好處:不改變原數組數據
import numpy as np;
y =np.array([24242, 43, 6, 46, 46, 4, 6, 4, 546]);

sortResult = np.argsort(y);

刪除列表中元素等於某值(eleVal)的全部元素

def delete(array,eleVal): # 刪除指定元素
    idx = -1;
    idx=array.index(eleVal)
    while idx >= 0  :
        del array[idx];
        idx = -1;
        try:
            idx=array.index(eleVal);
        except Exception as e:
            print("[delete] end to remove eleVal '",eleVal,"'!");
        pass;
delete(array,'j');

多維數組轉換爲一維數組

articleWords = [['文章', '數學'], ['權力']];
artcileWords = [i for item in articleWords for i in item]; # 二維詞彙矩陣合併爲一維數組 # 參考 :https://blog.csdn.net/kevin_7july/article/details/79289814

 ## output
 ['文章', '數學', '權力']
相關文章
相關標籤/搜索