[英]How to convert Complex Collection to 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))
真的非常感謝任何幫助。
你的問題是你在greeting
dictionary
,而不是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)
希望這可以幫助! 〜炮手
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.