random.choice from set? python(从集合中随机选择?Python)
问题描述
我正在研究猜谜游戏的人工智能部分.我想让 AI 从这个列表中随机选择一个字母.我将其作为一组进行,因此我可以轻松地从列表中删除字母,因为它们在游戏中被猜到,因此不再被猜到.
I'm working on an AI portion of a guessing game. I want the AI to select a random letter from this list. I'm doing it as a set so I can easily remove letters from the list as they are guessed in the game and are therefore no longer available to be guessed again.
它说 set
对象不可索引.我该如何解决这个问题?
it says set
object isn't indexable. How can I work around this?
import random
aiTurn=True
while aiTurn == True:
allLetters = set(list('abcdefghijklmnopqrstuvwxyz'))
aiGuess=random.choice(allLetters)
print (aiGuess)
推荐答案
注意(2020 年 10 月): 从 v3.9 开始,Python 有 正式弃用 random.sample()
在集合上工作,官方指导是在传入之前将集合显式转换为列表或元组,但这并不能解决效率问题.
Note (Oct. 2020): as of v3.9, Python has officially deprecated random.sample()
working on sets, with the official guidance being to explicitly convert the set to a list or tuple before passing it in, though this doesn't solve the efficiency problems.
>>> random.sample(set('abcdefghijklmnopqrstuvwxyz'), 1)
['f']
文档:https://docs.python.org/3/库/random.html#random.sample
请注意,无论您如何从集合中选择随机元素效率极低 - 它所花费的时间与集合的大小成正比,或者如果集合的底层哈希表由于稀疏而变得更糟删除元素.
Note that choosing random elements from a set is extremely inefficient no matter how you do it - it takes time proportional to the size of the set, or worse if the set's underlying hash table is sparse due to removed elements.
相反,您可能应该使用 不同的数据结构有效地支持此操作.
Instead, you should probably use a different data structure that supports this operation efficiently.
这篇关于从集合中随机选择?Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从集合中随机选择?Python


基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01