此代码生成一组无意义的随机名称:
def unique_names(k: int, ntokens: int,
pool: str=string.ascii_letters) -> set:
"""
Generate a set of unique string tokens.
k: Length of each token
ntokens: Number of tokens
pool: Iterable of characters to choose from
"""
seen = set()
join = ''.join
add = seen.add
while len(seen) < ntokens:
token = join(random.choices(pool, k=k))
add(token)
return seen而且起作用了。我现在正在尝试生成n digits_long integers的随机n digits_long integers数。
随机导入
def numbers(k: int ,n: int) -> set:
l = set()
join = ''.join
add = l.add
for _ in range(k):
n= join(["{}".format(randint(0, 9)) for num in range(0, n)])
add(n)
return l上面的代码如果只有一个数字:numbers(1,3) -> output {'134'},这是我的第一个问题。
我想要的是将一个pair, value数据集归纳为随机名称和数字,如下所示:
{'vffde':234234, 'hrtge': 342344, ....}因此,我需要修复第2段代码,并以某种方式使用这两个函数来gt结果字典的ramdom名称:数字。
我很难做到这一点。有人能帮我吗?
发布于 2021-09-23 17:13:25
您可以使用dict(zip(...))这样做:
def unique_names(k: int, ntokens: int,
pool: str = string.ascii_letters) -> set:
"""
Generate a set of unique string tokens.
k: Length of each token
ntokens: Number of tokens
pool: Iterable of characters to choose from
"""
seen = set()
join = ''.join
add = seen.add
while len(seen) < ntokens:
token = join(random.choices(pool, k=k))
add(token)
return seen
def numbers(k: int, n: int) -> set:
seen = set()
join = ''.join
add = seen.add
while len(seen) < k:
m = join(["{}".format(randint(0, 9)) for num in range(0, n)])
add(m)
return seen
random_pairs = dict(zip(unique_names(5,2), numbers(2, 6)))代码中有两个问题:n= join(["{}".format(randint(0, 9)) for num in range(0, n)])重用变量n,所以当k> 1时,将整数转换为字符串。如果您总是尝试至少拥有k条目,那么它也应该是一个while循环。
您还将k用于unique_names和numbers中的一个非常不同的目的。这目前不是一个bug,但是它极有可能导致更多与变量名称隐藏相关的bug。
https://stackoverflow.com/questions/69304159
复制相似问题