生成随机字母(奇数索引和偶数索引处)

2024-10-03 21:32:00 发布

您现在位置:Python中文网/ 问答频道 /正文

两个字符串,如:

import random
consonants = "bcdfghjklmnprstvwz"
vowels = "aeiou"

我想在偶数索引中得到四个字母,在奇数索引中得到三个字母,比如:

ejiguka / agewilu / isavonu (odd indexes(0,2,4,6),even indexes(1,3,5,7))

我试过这个函数,但不起作用。你知道吗

random_letter = random.choice(consonants[::2])
random_letter1 = random.choice(vowels[1::2])
random_together = random_letter + random_letter1

我得到了两个随机的字母,比如be,但是我想得到输出,比如ejiguka/agewilu。你知道吗


Tags: 字符串import字母random偶数choiceletterindexes
2条回答

您可以创建一个字母列表,并按如下方式将它们连接在一起:

str1 = ''.join(random.choice(consonants) if i % 2 else random.choice(vowels) for i in range(7))

您的代码只从每个列表中获取一个字母,并且只从切片项中获取一个字母。你知道吗

cons = (random.choice(consonants) for i in range(3))
vwls = (random.choice(vowels) for i in range(4))

''.join(next(cons) if i % 2 else next(vwls) for i in range(7))

你在正确的轨道上拼接,但你没有应用它的权利。你知道吗

首先初始化空列表:

In [134]: x = [None] * 7

现在,在拼接中赋值,使用random.sample检索唯一的随机字符子集:

In [135]: x[::2] = random.sample(vowels, 4)
     ...: x[1::2] = random.sample(consonants, 3)

加入并打印:

In [136]: ''.join(x)
Out[136]: 'ijepula' 

相关问题 更多 >