我GOOGLE了很多,但無法找到它。我想知道random.sample()
方法的用法,它給了什麼?何時應該使用它以及一些示例用法。python中的random.sample()方法是做什麼的?
10
A
回答
25
random.sample(人口中,k)
返回唯一元素的第k長度列表 從羣體中選擇的序列。用於沒有 替換的隨機抽樣。
基本上,它挑選ķ唯一的隨機元素,一個樣品,從一個序列:
>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]
random.sample
作品也直接從一個範圍:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
除了序列,random.sample
配套套裝太:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
然而,random.sample
不與任意迭代工作:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
+0
所以從給定的順序它會隨機選擇一個給定的no。的元素,對嗎? – kartikeykant18
+0
@kartikey_kant是的,就是這樣,很簡單。 – alecxe
相關問題
- 1. 的Python random.sample()
- 2. 什麼是在Python中做countif的好方法
- 3. 在Python中這樣做的最好方法是什麼?
- 4. jMock的with()方法是做什麼的?
- 5. 這樣做的方法是什麼?
- 6. IUrlHistoryStg :: BindToObject方法是做什麼的?
- 7. 做SlideAnimation的正確方法是什麼?
- 8. 這是做什麼的正確方法?
- 9. python中的list方法是什麼?
- 10. Python中的替代方法是什麼?
- 11. Python中的`import _preamble`是做什麼的?
- 12. 什麼是無效的,更新方法在VC++中做什麼
- 13. Python中的random.sample和random.shuffle有什麼區別
- 14. 用python做旋轉日誌的正確方法是什麼?
- 15. 在python中,len(list)是做什麼的?
- 16. 在Python中,pydoc是做什麼的?
- 17. 在Python Docstrings中,「:obj:`是做什麼的?
- 18. 什麼是LINQ'ish的做法
- 19. clog()的做法是什麼?
- 20. 方法定義中的operator +做什麼?
- 21. 查詢方法中的String []做什麼?
- 22. Python中的[0] * x語法是做什麼的?
- 23. 在Python中做這種排序的標準方式是什麼?
- 24. 對象的__init __()方法在python中做什麼?
- 25. 在Python中別名方法名的最好方法是什麼?
- 26. 方法python方法簽名中_ = None的意義是什麼?
- 27. 在python中派生類方法的正確方法是什麼?
- 28. 什麼是在Python類中排序方法的好方法?
- 29. Python的locals()是做什麼的?
- 30. 這是什麼做的(Python)的
http://docs.python.org/2/library/random.html#random.sample – sshashank124
http://stackoverflow.com/questions/22577916/using-nested-loops-to-generate-3-different-random-numbers/22577977#22577977 –