如何在Python中声明单个数组值?

Swi*_*ick 1 python xmpp

我目前正在使用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]
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 7

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

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']
Run Code Online (Sandbox Code Playgroud)

或者,您可以通过定义空列表来构建列表,然后附加元素:

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')
Run Code Online (Sandbox Code Playgroud)

我强烈建议您在继续之前阅读Python教程,它解释了构建python类型以及如何为您操作它们.