python取列表前几个元素_Python下几种从一个序列中取出元素的方法
使用Python進行數據處理時,有時候會有這樣的操作,比如從一個列表或者numpy array中隨機取出一個元素,對一個列表中的元素進行shuffle,等等。雖然這些操作也可以通過編寫很簡短的程序完成,但我們使用Python有一點很重要,就是不要重復遭輪子,如果有輪子可以直接拿來用,為什么不省時省力地去用呢?
1.從序列中隨機取出一個或多個元素
使用random模塊的sample函數:
從列表lst或numpy array中隨機取出k(當然,k要小于等于lst中元素的個數)個元素:random.sample(lst, k)
import random
lst = range(20)
print(random.sample(lst, 1)) #取出1個元素
print(random.sample(lst, 5)) #取出多個元素
import random
lst = range(20)
print(random.sample(lst, 1)) #取出1個元素
print(random.sample(lst, 5)) #取出多個元素
import random
lst = range(20)
print(random.sample(lst, 1)) #取出1個元素
print(random.sample(lst, 5)) #取出多個元素
2.對一個序列中的元素進行shuffle
其實如果使用1中的sample函數,從lst中隨機取出所有元素,也就實現了對列表中元素進行shuffle的目的。
import random
lst = range(20)
print(random.sample(lst, len(lst)))
import random
lst = range(20)
print(random.sample(lst, len(lst)))
import random
lst = range(20)
print(random.sample(lst, len(lst)))
也有另一種方法,使用numpy的random下的permutation函數,即:np.random.permutation。該函數直接輸入一個序列,即返回shuffle后的該序列。其參數可以為列表,也可以為numpy array。
import numpy as np
nda = np.array(range(20))
print(np.random.permutation(nda))
import numpy as np
nda = np.array(range(20))
print(np.random.permutation(nda))
import numpy as np
nda = np.array(range(20))
print(np.random.permutation(nda))
3.從序列中取出固定長度的所有組合
有時候我們需要從序列中取出固定長度的所有組合,比如一個有10個元素的列表,我們從中取出所有元素的兩兩組合,即取出長度為2的所有組合,可以使用itertools模塊的combinations函數:
import itertools
lst = range(10)
print(list(itertools.combinations(lst, 2)))
import itertools
lst = range(10)
print(list(itertools.combinations(lst, 2)))
import itertools
lst = range(10)
print(list(itertools.combinations(lst, 2)))
上面的程序中,因為itertools的函數返回的是一個iterator,所以需要用list將其轉為列表,然后打印輸出。
4.從序列中取出元素的所有排列組合
有時候我們需要從序列中取出元素的所有組合,比如,如果列表中的每個元素對應于一個模型的效果,我們想看不同模型ensamble起來的結果,來找到最優組合,就需要這種操作。
還是使用itertools的combinations函數,如下:
import itertools
lst = range(5)
for i in range(len(lst)):
_lst = itertools.combinations(lst, i+1)
print(_lst)
import itertools
lst = range(5)
for i in range(len(lst)):
_lst = itertools.combinations(lst, i+1)
print(_lst)
import itertools
lst = range(5)
for i in range(len(lst)):
_lst = itertools.combinations(lst, i+1)
print(_lst)
該函數返回的是一個iterable,所以打印顯示前需要用list轉化一下。
如果取出元素的順序不同也算不同的方式,即取出元素的所有排列呢?可以使用itertools的permutations函數,如下:
import itertools
lst = range(5)
print(list(itertools.permutations(lst)))
print(list(itertools.permutations(lst, 3)))
import itertools
lst = range(5)
print(list(itertools.permutations(lst)))
print(list(itertools.permutations(lst, 3)))
import itertools
lst = range(5)
print(list(itertools.permutations(lst)))
print(list(itertools.permutations(lst, 3)))
該函數返回的也是一個iterable,所以打印顯示前也需要用list轉化一下。
此外,該函數可以傳一個長度的參數,以示取出的排列長度。
總結
以上是生活随笔為你收集整理的python取列表前几个元素_Python下几种从一个序列中取出元素的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 传统的线性降维方法效果不佳。_10分钟数
- 下一篇: 5、this调用语句必须是构造函数中的第