Pau*_*arr 6 python random list indices
从两个列表开始,例如:
lstOne = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
lstTwo = [ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
Run Code Online (Sandbox Code Playgroud)
我想让用户输入他们想要提取的项目数,占总列表长度的百分比,以及每个列表中随机提取的相同索引.例如,说我想要50%的输出
newLstOne = ['8', '1', '3', '7', '5']
newLstTwo = ['8', '1', '3', '7', '5']
Run Code Online (Sandbox Code Playgroud)
我使用以下代码实现了这一点:
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
Run Code Online (Sandbox Code Playgroud)
但是我想知道是否有更有效的方法来实现这一点,在我的实际使用案例中,这是145,000个项目的子样本.此外,randrange是否足够没有这种规模的偏见?
谢谢
Q. I want to have the user input how many items they want to extract, as a percentage of the overall list length, and the same indices from each list to be randomly extracted.
A.最直接的方法直接符合您的规范:
percentage = float(raw_input('What percentage? '))
k = len(data) * percentage // 100
indicies = random.sample(xrange(len(data)), k)
new_list1 = [list1[i] for i in indicies]
new_list2 = [list2[i] for i in indicies]
Run Code Online (Sandbox Code Playgroud)
Q. in my actual use case this is subsampling from 145,000 items. Furthermore, is randrange sufficiently free of bias at this scale?
答:在Python 2和Python 3中,random.randrange()函数完全消除了偏差(它使用内部_randbelow()方法进行多次随机选择,直到找到无偏差结果).
在Python 2中,random.sample()函数略有偏差,但仅在最后53位的舍入中.在Python 3中,random.sample()函数使用内部_randbelow()方法,并且没有偏差.