2016-05-16 57 views
1

試圖創建一個非常基本的腳本,它將顯示一組字符串中的隨機字符串。但是,我需要將它顯示爲打印功能(即沒有括號或逗號)。我曾嘗試使用加入,並遇到一個錯誤(難以置信的類型:列表)如何將複雜集合轉換爲字符串?

name = ("Tom") 
greeting = { 
["Hello", name, "How are you today?"], 
["Welcome", name, "How was your day?"], 
["Greetings", name, "Shall we play a game?"], 
["Well hey there", name, "Whats up?"], 
} 
print (', '.join(greeting)) 

任何幫助真的很不勝感激。

+0

問候應該是一本字典嗎?或者列表來保存你的列表? –

回答

0

您的問題是您正在製作greeting a dictionary,而不是 a list

我的繼承人修復你的代碼工作:

#allows us to use randint function 
from random import randint 

name = ("Tom") 

#change greeting from a dictionary to a list by replacing { with [ 
greeting = [ 
["Hello", name, "How are you today?"], 
["Welcome", name, "How was your day?"], 
["Greetings", name, "Shall we play a game?"], 
["Well hey there", name, "Whats up?"], 
] 
#assign myGreeting as a random num between 0 and 3 
myGreeting = randint(0,len(greeting)-1) 

#define out output to be printed to console (its a String) 
output = "" 

#itterate through our random greeting word by word and 
#concatinate to output variable one word at a time 
for myWord in greeting[myGreeting]: 
     output+=myWord+" " 

print (output) 

輸出: enter image description here

希望這有助於! 〜槍手

相關問題