【发布时间】:2014-06-20 23:22:32
【问题描述】:
从两个列表开始,例如:
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
但我想知道是否有更有效的方法来执行此操作,在我的实际用例中,这是从 145,000 个项目中进行二次抽样。此外, randrange 在这个尺度上是否充分没有偏差?
谢谢
【问题讨论】:
-
@devnull 您过于激进地将问题标记为可能的重复问题。另一个问题是“我如何制作随机样本”。这个问题提出了两个更有趣的问题,“我如何从多个列表中制作相同的样本”和“内置随机函数是否有偏差”。
-
@RaymondHettinger 白天早些时候观看了您的一个 Python 视频,我怎么能反驳呢? (关闭投票被撤回。)
标签: python list random indices python-internals