将变量存储在列表python中

时间:2019-02-26 22:21:55

标签: python python-3.x

所以我尝试执行此操作,并且我认为它很清楚,我想将我创建的消息变量存储在列表中,然后将其用于打印,我想知道为什么这行不通吗? / p>

items = ['item1', 'item2', 'item3']
message1 = "This is " + items[0] + "its color is red"
message2 = "This is " + items[1] + "its color is blue"
message3 = "This is " + items[2] + "it has no color yet"
messages = ['message1', 'message2', 'message3']
for message in messages:
    print(message)

输出为:

message1
message2
message3

3 个答案:

答案 0 :(得分:3)

删除引号

messages = [message1, message2, message3]

当前,您只打印字符串而不是变量

也是

for message in messages:
    print(messages)

messages打印整个列表3次。更改为print(message)以打印列表中的每个项目

答案 1 :(得分:2)

这是字符串列表:

['message1', 'message2', 'message3']

您要查找的是变量列表:

[message1, message2, message3]

答案 2 :(得分:1)

message1 = "This is " + items[0] + "its color is red"
message2 = "This is " + items[1] + "its color is blue"
message3 = "This is " + items[2] + "it has no color yet"
messages = [message1, message2, message3]
for message in messages:
    print(messages)

您确实很接近,但是您要列出的是字符串列表,而不是变量列表。只是把报价拿出来!