如何一次从列表中打印出n(3)个项目,然后将它们显示在一行上.的Python 3 [英] How to print out n (3) items from a list at a time and then display them on one line. Python 3

查看:84
本文介绍了如何一次从列表中打印出n(3)个项目,然后将它们显示在一行上.的Python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从下面的代码中可以看到,我的程序将文本从文本文件(homework.txt)读取到名为heightandweight的列表中.然后让我一次打印列表中的3个项目.但是,它不会在一行上打印3条信息.我该怎么办?

As you can see from the code below, I have my program read text from a text file (homework.txt) to a list called heightandweight. I then have it print 3 items in the list at a time. However it doesn't print the 3 pieces of information on one line. How would I do that?

myFile = open("homework.txt","rt")
heightandweight = []

for line in myFile:
    line = line.strip("\n")
    heightandweight.append(line)

print(heightandweight)
myFile.close()

for e in range (0, len(heightandweight),3):
    for i in heightandweight[e:e+3]:
        print (i)

上面的代码将输出:

['James', '73', '1.82', 'Peter', '78', '1.80', 'Jay', 'Beth', '65', '1.53', 'Mags', '66', '1.50', 'Joy', '62', '1.34']
James
73
1.82
Peter
78
1.80
Jay
Beth
65
1.53
Mags
66
1.50
Joy
62
1.34             

推荐答案

如果您不想使用格式字符串(即,如果只想打印一组数据而没有换行符),则可以防止换行符,使用:

If you don't want to use format strings (i.e. if you just want to print out a set of data without having a newline) then you can prevent a newline by using:

print data,

或者,如果您使用的是Python 3:

or, if you're using Python 3:

print(data, end="")

假设是后者,您的代码将如下所示:

Assuming the latter, your code would then look like:

for e in range (0, len(heightandweight),3):
    for i in heightandweight[e:e+3]:
        print(i, end="")
    print("")

这篇关于如何一次从列表中打印出n(3)个项目,然后将它们显示在一行上.的Python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆