我试着写一个程序,你输入一个元音或一个辅音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
答案 0 :(得分: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")
答案 1 :(得分:6)
将列表中的字母更改为设置:
letters = set()
>>> letters.add('x')
>>> letters.add('x')
>>> letters
set(['x'])
供参考:Python sets
编辑:刚刚注意到你要求的东西不同于一套工作,eumiro的答案就是你要找的东西。如果你想保留这个作为参考,那很好,否则我会删除我的答案
答案 2 :(得分:2)
你可以这样做
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()
答案 3 :(得分:1)
在将列表添加到列表之前,检查列表是否已包含辅音或元音可能是个好主意。例如,这里将是带有这种检查的while循环:
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")
内部while循环是这样的,如果随机选择已经在列表中,程序会选择另一个字母。