我目前正在玩python-jabberbot,并且在创建发送随机句子的简单方法时遇到了麻烦。我不精通python,所以我想知道哪里出错了。我有一种宣告数组是我的失败的感觉:

def whatdoyouknow(self, mess, args):
        """random response"""
        string[0] = 'this is a longish sentence about things'
        string[1] = 'this is a longish sentence about things number 2'
        string[2] = 'this is a longish sentence about things number 3'

        i = random.randint(0, 2)
        return string[i]

最佳答案

您可以通过将元素放在方括号中来定义列表文字:

string = ['this is a longish sentence about things',
          'this is a longish sentence about things number 2',
          'this is a longish sentence about things number 3']


另外,您可以通过定义一个空列表,然后附加元素来构建列表:

string = []
string.append('this is a longish sentence about things')
string.append('this is a longish sentence about things number 2')
string.append('this is a longish sentence about things number 3')


我强烈建议您先阅读Python tutorial,然后再继续进行操作,它说明了构建python类型以及如何为您操纵它们的方法。

10-05 22:57