打印不属于for循环的变量的输出

2024-06-12 09:55:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个for循环,将每三行输出连接在一起

for n in range(len(z)//3):
    l.append(''.join(z[n*3:n*3+3]))
    test = "\n".join(l)
print test

Z是一个文本列表,我还有另一个变量,不是for循环的一部分,而是在代码的其他地方使用的。我想打印这个变量以及每行的test,例如:

z = ['red', 'or', 'black', 'odd', 'or', 'even', 'yes', 'or', 'no']

测试输出为

red or black
odd or even
yes or no

我想添加另一个变量到打印例如变量是“u”,其中有文本“你决定?”所以我的输出是:

red or black you decide?
odd or even you decide?
yes or no you decide?

当我打印测试时,u它只打印最后一行的u,而不是每一行。你知道吗


Tags: ornointest文本youforrange
2条回答
l.append(''.join(z[n*3:n*3+3]) + u) # concatenate the message string

只需在l.append(''.join(z[n*3:n*3+3]))行中使用函数^{}进行更改

l.append("{} you decide?".format(' '.join(z[n*3:n*3+3])))

完整的程序

z = ['red', 'or', 'black', 'odd', 'or', 'even', 'yes', 'or', 'no']
l = []
u = "you decide?"
for n in range(len(z)//3):
    l.append("{} {}".format(' '.join(z[n*3:n*3+3])),u)
    test = "\n".join(l)
print test

以及输出

red or black you decide?
odd or even you decide?
yes or no you decide?

相关问题 更多 >