Python随机文字

rn0zuynd  于 2023-05-21  发布在  Python
关注(0)|答案(1)|浏览(162)

给定以下自定义Literal

from typing import Literal, get_args

_ACTIONS = Literal["pasteCharAt", "copyCharAt", "deleteCharAt", "replaceCharAt",
                   "selectAll", "deleteAll", "copyAll", "pasteAllAt", "click",
                   "moveLeft", "moveRight"]

我怎样才能产生随机选择它的选项?
为了

print(f'random.choice(_ACTIONS) = {random.choice(_ACTIONS)}')

我只有:

File "C:\python38\lib\random.py", line 288, in choice
    i = self._randbelow(len(seq))
TypeError: object of type '_GenericAlias' has no len()

对于以下尝试:

print(f'random.choice(list(_ACTIONS)) = {random.choice(list(_ACTIONS))}')

我也得到了一个错误:

File "C:\python38\lib\typing.py", line 261, in inner
    return func(*args, **kwds)
  File "C:\python38\lib\typing.py", line 685, in __getitem__
    params = tuple(_type_check(p, msg) for p in params)
  File "C:\python38\lib\typing.py", line 685, in <genexpr>
    params = tuple(_type_check(p, msg) for p in params)
  File "C:\python38\lib\typing.py", line 149, in _type_check
    raise TypeError(f"{msg} Got {arg!r:.100}.")
TypeError: Parameters to generic types must be types. Got 0.

我使用Python 3.8.6,如果这很重要的话。

e4eetjau

e4eetjau1#

您可以使用get_args()将Literal转换为元组,然后再尝试将其与random.choice()一起使用。下面是一个例子:

import random
from typing import Literal, get_args

_ACTIONS = Literal["pasteCharAt", "copyCharAt", "deleteCharAt", "replaceCharAt",
                   "selectAll", "deleteAll", "copyAll", "pasteAllAt", "click",
                   "moveLeft", "moveRight"]

# Convert Literal to a tuple
actions_tuple = get_args(_ACTIONS)

# Use random.choice with the tuple
print(f'random.choice(actions_tuple) = {random.choice(actions_tuple)}')

# Sample output:
# random.choice(actions_tuple) = replaceCharAt

这应该给予从定义的_ACTIONS Literal中随机选择。

相关问题