简体   繁体   中英

How to print out n (3) items from a list at a time and then display them on one line. Python 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)

The above code will output:

['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             

You probably need to learn about formatting strings in python. In your case the relevant code would be something like:

for e in range (0, len(heightandweight),3):
    string="{} {} {}".format(heightandweight[e], heightandweight[e+1], heightandweight[e+2])
    print(string)

Which could be compressed into just:

for e in range (0, len(heightandweight),3):
    print("{} {} {}".format(heightandweight[e], heightandweight[e+1], heightandweight[e+2]))

However it would be much neater to have the original text file be organised like this in columns:

James 73 1.82
Peter 78 1.80
Beth 65 1.53
Mags 66 1.50
Joy 62 1.34

Then your code could be simplified to:

with open("homework.txt","rt") as myFile:
    for line in myFile:
        name, height, weight = line.split(' ')
        print("{} {} {}".format(name, height, weight))

If you don't want to use format strings (ie 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,

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("")

With python it is very easy. I recommend you strongly to check the function join ( https://docs.python.org/3/library/stdtypes.html#str.join ).

I am not sure if this is why you want but you can test this :

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

simple iterator:

lst=['James', '73', '1.82', 'Peter', '78', '1.80', 'Jay', 'Beth', '65', '1.53', 'Mags', '66', '1.50', 'Joy', '62', '1.34']
lst_copy=lst #if You need to use oryginal lst later use it, otherwise dont
for i in range(len(lst)):
    try:lst[i]=float(lst[i])
    except:pass
for i in range(0,len(lst),3):
    try:
        if type(lst_copy[i+1])!=float:
            print(lst_copy[i])
            lst_copy.pop(i)
        else:
            print(i,lst_copy[i:i+3])
    except:pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM