试图按百分比分割列表

时间:2014-04-25 17:04:40

标签: python

我试图通过获取一个百分比来拆分列表,然后将主要列表中的元素随机地抓取到另外两个列表中。 trainingSet是左上方列表。当我生成随机索引来挑选时,我遇到了问题。这段代码适用于一个小列表,但当我使用(len(rawRatings)= 1000)时,它不起作用。

错误:

  File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 1, in <module>
      # Used internally for debug sandbox under external interpreter
    File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 29, in partitionRankings
    File "/Users/rderickson9/anaconda/lib/python2.7/random.py", line 241, in randint
return self.randrange(a, b+1)
    File "/Users/rderickson9/anaconda/lib/python2.7/random.py", line 217, in randrange
      raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
  ValueError: empty range for randrange() (0,0, 0)

raw Ratings是一个列表,testPercent是一个浮点数。

离。

rawRatings = [(123,432,4),(23,342,3),(23,123,5),(234,523,3),(34,23,1), (12,32,4)]
testPercent = .2
partitionRankings(rawRatings, testPercent)
[(23,123,5),(234,523,3),(34,23,1),(123,432,4),(12,32,4)],[(23,342,3)]


def partitionRankings(rawRatings, testPercent):
    testSet = []
    trainingSet = []
    howManyNumbers = int(round(testPercent*len(rawRatings)))
    declineRandom = 0
    while True:
        if declineRandom == howManyNumbers:
                    break        
        randomIndex = random.randint(0, (len(rawRatings)-1)-declineRandom)
        testSetTuple = rawRatings[randomIndex]
        del rawRatings[randomIndex]
        testSet.append(testSetTuple)

        declineRandom = declineRandom + 1
    trainingSet = rawRatings[:]
    return (trainingSet), (testSet)

我不想选择相同的随机索引。有一次,我选择一个,我不想再次随机选择它。我不认为这是正确的。这是我遇到麻烦的部分。

randomIndex = random.randint(0, (len(rawRatings)-1)-declineRandom)

1 个答案:

答案 0 :(得分:8)

由于训练集的顺序无关紧要,您可以使用完全不同的策略执行此操作 - 随机播放rawRating列表,然后将第一个howManyNumbers元素作为测试集,其余为您的训练集。

import random

def partitionRankings(rawRatings, testPercent):
    howManyNumbers = int(round(testPercent*len(rawRatings)))
    shuffled = rawRatings[:]
    random.shuffle(shuffled)
    return shuffled[howManyNumbers:], shuffled[:howManyNumbers]

至于为什么你的代码不起作用,正如你猜测的那样,问题在于这一行:

randomIndex = random.randint(0, (len(rawRatings)-1)-declineRandom)

问题在于-declineRandom

  • 每次进行循环时,都会删除您选择的条目,因此即使您再次获得相同的索引,也不会选择相同的元素。
  • 如果你没有在每次迭代中从列表中删除元素,这不会阻止选择相同的元素两次 - 这只会阻止你选择任何最后的declineRandom元素。
    • 您必须在每次迭代时将元素移动到列表的末尾。
  • 由于您删除了元素,然后在列表末尾不替换它们,len(rawRatings)会在declineRandom增长时缩小。
    • 如果您有1000个项目的列表并尝试在测试集中放入600,那么当您在测试集中有550个项目时,您将尝试获得大于或等于零且小于或等于0的随机int。等于(450-1)-550=-101。显然你不会真正达到这一点,但希望它能使问题变得清晰。
相关问题