我正在尝试创建一个程序,其中计算机从列表中随机选择一个单词,然后将该单词的字母随机排列,这是行不通的。为什么它不起作用?
import random
mysports= ["swimming" , "basketball" , "soccer" , "cross country" ,
"football" , "cross-country skiing"]
letters = mysports[0]
letters1 = mysports[1]
letters2 = mysports[2]
letters3 = mysports[3]
letters4 = mysports[4]
letters5 = mysports [5]
a = (random.choice(mysports))
if a == mysports[0]:
b = random.shuffle(letters)
print (b)
elif a == mysports[1]:
c = random.shuffle(letters1)
print (c)
elif a == mysports[2]:
d = random.shuffle(letters2)
print (d)
elif a == mysports[3]:
e = random.shuffle(letters3)
print (e)
elif a == mysports[4]:
f = random.shuffle(letters4)
print (f)
elif a == mysports[5]:
g = random.shuffle(letters5)
print (g)
这是我尝试运行它时给我的:
回溯(最近一次通话最近):文件“ python”,第23行,在 TypeError:“ str”对象不支持项目分配
答案 0 :(得分:1)
random.shuffle()只能随机播放列表。要执行您想要的操作,必须将单词的字母变成一个列表。
我建议这样做
import random
mysports= ["swimming" , "basketball" , "soccer" , "cross country" ,
"football" , "cross-country skiing"]
letters = mysports[0]
letters1 = mysports[1]
letters2 = mysports[2]
letters3 = mysports[3]
letters4 = mysports[4]
letters5 = mysports [5]
a = random.choice(mysports)
aList = []
for char in a:
aList.extend(char)
random.shuffle(aList)
aString = ""
for char in aList:
aString += char
print(aString)
它会做您想做的事,而且效率更高。