string - 使用列表的字符串/元素为 random.sample 提供范围

标签 string python-3.x random range sample

我想创建一个包含 3-7 个随机字母名称的变量。 (名字不对也没关系)。我知道如何让它包含 3 个字母,但我不知道如何处理带有字母的范围(字符串/列表)。到目前为止,这是我的代码:

import random
ABC = ['A', 'Á', 'B', 'C'... just imagine every single letter of the Hungarian alphabet as a list]
name = random.sample(ABC, 3)

我试着这样做:

name = random.sample(ABC, 3) or random.sample(ABC, 4)

当然,这并没有奏效。你们能帮帮我吗? :)

最佳答案

random.sample(ABC, 3) 返回一个列表。如下

>>> random.sample(ABC, 3)
['q', 'h', 'x']

您可以使用join 方法将其转换为字符串

>>> a = random.sample(ABC, 3)
>>> a 
['q', 'h', 'x']
>>>''.join(a)
'qhx'

编辑:您甚至可以使用 randint 选择 3 到 7 之间的数字随机模块

>>> a = random.sample(ABC, random.randint(3,7))
>>> ''.join(a)
'bvt'
>>> b = random.sample(ABC, random.randint(3,7))
>>> ''.join(b)
'fycu'

关于string - 使用列表的字符串/元素为 random.sample 提供范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46900698/

相关文章:

unit-testing - 从 reduceByKey() 调用函数时单元测试期间的导入错误

python - 使用总和为常数的 N 个随机数创建类泊松分布 (C)

java - 在每个第 n 个字符处拆分一个字符串

javascript - 从字符串列表中删除前缀

mysql - 我的问题是关于 mysql 中 Like 命令中的多个 % 运算符

python - 如何在 python 中创建 10,000 个随机坐标?

python - 根据随机数打开唯一的文本文件

c - 如何根据位的位置随机选择一个值

string - 为什么在文本编辑器的查找功能中选择 "BM algorithm"而不是 "Sunday algorithm"?

c - 在 while 循环中使用 scanf 读取带有空格的用户输入?