简体   繁体   English

random.shuffle如何导致KeyError?

[英]How can random.shuffle result in a KeyError?

I just got the error: 我刚收到错误:

Traceback (most recent call last):
  File "./download_documents.py", line 153, in <module>
    paragraphs, used_pages = find_pages(lang, to_extract)
  File "./download_documents.py", line 67, in find_pages
    random.shuffle(page_titles_queue)
  File "/usr/lib/python2.7/random.py", line 291, in shuffle
    x[i], x[j] = x[j], x[i]
KeyError: 1

Which confuses me quite a bit. 这让我很困惑。

  1. random.shuffle seems to work on zero-element lists and on one-element lists. random.shuffle似乎适用于零元素列表和单元素列表。
  2. page_titles_queue is a list of tuples. page_titles_queue是一个元组列表。
  3. Two lines after the random.shuffle(page_titles_queue) , there is page_titles_queue.pop() , but that should not affect the shuffle. random.shuffle(page_titles_queue) 之后的两行,有page_titles_queue.pop() ,但这不应该影响shuffle。 Right? 对?

So what are possible reasons for the KeyError? 那么KeyError的可能原因是什么?

I use Python 2.7.12 on Ubuntu 16.04. 我在Ubuntu 16.04上使用Python 2.7.12

random.shuffle just exchanges items, the line where the exception happened makes this perfectly clear: random.shuffle只是交换项目,发生异常的random.shuffle这一点非常清楚:

x[i], x[j] = x[j], x[i]

Where x is the "sequence" that was passed in. In this case i and j will be values in the range range(0, len(x)) and if any of these i or j isn't present in the "sequence" it will throw an Exception . 其中x是传入的“序列”。在这种情况下, ij将是范围range(0, len(x))并且如果“序列”中不存在这些ij任何一个它会抛出Exception In your case it's very likely given that it throws a KeyError : 在你的情况下,它很可能会抛出一个KeyError

>>> import random
>>> d = {i: i for i in range(7, 10)}
>>> random.shuffle(d)
KeyError: 3

However it works by exchanging the values in case the dictionary contains exactly the keys that make up the range(0, len(x)) : 但是,如果字典包含组成range(0, len(x))的键range(0, len(x))它的工作方式是交换值:

>>> d = {i: i for i in range(10)}
>>> random.shuffle(d)
>>> d
{0: 7, 1: 9, 2: 3, 3: 4, 4: 0, 5: 2, 6: 1, 7: 6, 8: 8, 9: 5}

If one or multiple keys are missing it could work or it could throw an Exception . 如果缺少一个或多个密钥,它可能会起作用,或者它可能会抛出Exception That depends on which random numbers will be drawn: 这取决于将绘制哪些随机数:

d = {i: i for i in range(1, 10)}
random.shuffle(d)   # works sometimes, but sometimes it throws the KeyError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM