2016-05-16 26 views
1

Der Versuch, ein sehr einfaches Skript zu erstellen, das eine zufällige Zeichenfolge aus einer Gruppe von Zeichenfolgen anzeigt. Ich muss es jedoch so anzeigen, als wäre es eine Druckfunktion (d. H. Ohne Klammern oder Kommas). Ich habe versucht mit einem Join und ein Fehler auftritt (unhashable Typ: Liste)Wie konvertiert man komplexe Sammlung in String?

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)) 

Jede Hilfe wäre wirklich sehr zu schätzen.

+0

Soll Begrüßung ein Wörterbuch sein? Oder eine Liste, um Ihre Listen zu halten? –

Antwort

0

Ihr Problem war, dass Sie greeting eine dictionary statt eine list machten.

Heres mein fix an Ihrem Code, das funktioniert:

#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) 

Ausgang: enter image description here

hoffe, das hilft! ~ Gunner

Verwandte Themen