4

我正在尝试编写一个程序,您可以在其中输入元音或辅音 8 次,然后显示您选择的字母列表。有没有办法对其进行编程,以使同一个字母不会出现两次,例如,如果您选择元音并得到字母 a,那么字母 a 不能再次随机选择?这是到目前为止的程序:

lt = 0
letters = []
while lt<8:
    letter = raw_input("Please enter v for a Vowel or c for a Consonant: ")
    if letter == "c":
        letters.append(random.choice(consonant)),
        lt = lt + 1
    elif letter == "v":
        letters.append(random.choice(vowel)),
        lt = lt + 1
    else:
        print("Please enter only v or c")

print ("letters:")
print letters
4

4 回答 4

8

创建一个包含所有辅音和所有元音的列表,shuffle它们是随机的,然后一次取一个元素:

import random

con = list('bcdfghjklmnpqrstvwxyz') # in some languages "y" is a vowel
vow = list('aeiou')
random.shuffle(con)
random.shuffle(vow)
# con is now: ['p', 'c', 'j', 'b', 'q', 'm', 'r', 'n', 'y', 'w', 'f', 'x', 't', 'g', 'l', 'd', 'k', 'h', 'z', 'v', 's'] or similar
# vow is now: ['e', 'u', 'i', 'a', 'o'] or similar

letters = []
while len(letters) < 8:
    letter = raw_input("Please enter v for a Vowel or c for a Consonant: ")
    if letter == "c":
        if con:
            letters.append(con.pop())
        else:
            print("No more consonnants left")
    elif letter == "v":
        if vow:
            letters.append(vow.pop())
        else:
            print("No more vowels left")
    else:
        print("Please enter only v or c")
于 2012-12-10T14:39:26.060 回答
6

将字母从列表更改为设置:

letters = set()
>>> letters.add('x')
>>> letters.add('x')
>>> letters
set(['x'])

供参考:Python 集

编辑:刚刚注意到您要求的东西与集合的工作方式不同,eumiro 的答案就是您要寻找的东西。如果您想保留此内容以供参考,那很好,否则我将删除我的答案

于 2012-12-10T14:41:01.740 回答
2

you can do this

lt = {}
while len(lt.keys()) < 8:
    letter = raw_input("Please enter v for a Vowel or c for a Consonant: ")
    added == false
    while added != true:
        if letter == "c":
            toAdd = random.choice(consonant)
        elif letter == "v":
            toAdd = random.choice(vowel)
        else:
            print("Please enter only v or c")
        if not lt.has_key(toAdd): 
            lt[toAdd] = 1
            added = false
    letters = lt.keys()
于 2012-12-10T14:44:27.390 回答
1

It probably would be a good idea to check if the list already contained the consonant or vowel right before you added it to the list. For example, here would be the while loop with such checks:

while lt<8:
    letter = raw_input("Please enter v for a Vowel or c for a Consonant: ")
if letter == "c":
    c = random.choice(consonant)
    while c not in letters:
        c = random.choice(consonant)
    letters.append(random.choice(consonant))
    lt = lt + 1
elif letter == "v":
    v = random.choice(vowel)
    while v not in letters:
        v = random.choice(vowel)
    letters.append(random.choice(vowel))
    lt = lt + 1
else:
    print("Please enter only v or c")

The inner while loops are so that if the random choice is already in the list, the program chooses another letter.

于 2012-12-10T14:43:00.623 回答