2024-04-23 22:19:48 发布
网友
我使用这个Python代码从5个单词中随机选择3个单词来形成一条消息。在
def randomMessage(): word = ['Animal', 'Dog', 'Cat', 'Queen', 'Bird'] return (random.sample(word, 3))
然后,在后面的代码中,我想用
但它给了我一个错误:“必须是str,而不是一个列表”。在
我该怎么解决这个问题?在
您需要在list上使用^{}。在
list
调用random.sample(word, 3)返回一个list,因此要将其转换为string(每个元素之间有空格),您需要执行如下操作:
random.sample(word, 3)
string
' '.join(random.sample(word, 3))
这样可以得到:
因此,要完成答案,您需要修改randomMessage()函数末尾的行,使整个过程:
randomMessage()
def randomMessage(): word = ['Animal', 'Dog', 'Cat', 'Queen', 'Bird'] return ' '.join(random.sample(word, 3))
一些测试显示它现在返回一个string:
>>> randomMessage() 'Animal Queen Bird' >>> randomMessage() 'Cat Dog Animal' >>> randomMessage() 'Animal Cat Bird' >>> randomMessage() 'Bird Dog Animal'
您的方法返回一个列表,而不是字符串。最快的解决方法
return " ".join(random.sample(word, 3))
或者你可以说得更清楚
注意:在Python中使用此样式:random_message,而不是camelcaserandomMessage
random_message
randomMessage
您需要在} 。在
list
上使用^{调用
random.sample(word, 3)
返回一个list
,因此要将其转换为string
(每个元素之间有空格),您需要执行如下操作:这样可以得到:
^{pr2}$因此,要完成答案,您需要修改
randomMessage()
函数末尾的行,使整个过程:一些测试显示它现在返回一个
string
:您的方法返回一个列表,而不是字符串。最快的解决方法
或者你可以说得更清楚
^{pr2}$注意:在Python中使用此样式:
random_message
,而不是camelcaserandomMessage
相关问题 更多 >
编程相关推荐