python从列表中随机提取多个元素_使用python从列表中随机提取x项

从两个列表开始,例如:lstOne = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

lstTwo = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

我想让用户输入他们想要提取多少项,占整个列表长度的百分比,以及从每个列表中随机提取的相同索引。比如说我想要50%的产量newLstOne = ['8', '1', '3', '7', '5']

newLstTwo = ['8', '1', '3', '7', '5']

我使用以下代码实现了这一点:from random import randrange

lstOne = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

lstTwo = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

LengthOfList = len(lstOne)

print LengthOfList

PercentageToUse = input("What Percentage Of Reads Do you want to extract? ")

RangeOfListIndices = []

HowManyIndicesToMake = (float(PercentageToUse)/100)*float(LengthOfList)

print HowManyIndicesToMake

for x in lstOne:

if len(RangeOfListIndices)==int(HowManyIndicesToMake):

break

else:

random_index = randrange(0,LengthOfList)

RangeOfListIndices.append(random_index)

print RangeOfListIndices

newlstOne = []

newlstTwo = []

for x in RangeOfListIndices:

newlstOne.append(lstOne[int(x)])

for x in RangeOfListIndices:

newlstTwo.append(lstTwo[int(x)])

print newlstOne

print newlstTwo

但我想知道是否有一种更有效的方法来实现这一点,在我的实际用例中,这是从145000个项目中进行的子抽样。此外,randrange在这个尺度上是否足够没有偏见?

谢谢你


版权声明:本文为weixin_39849479原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。