简体   繁体   中英

Lists in python 3.x

from random import randint

List = [randint(0,99) for i in range(20)]
print("%3s" % List)
List.sort()
print("%3s" % List)

so i've been working on this code to give me a random list of 20 inputs between 0 and 99. Did i do the print statements correctly so that it would print 20 per line with a field with of 3? Im assuming field with means xx9 or x98 etc?

No, you didn't do the print format correctly. You have a single %s format, which is correct to print a string. Adding the 3, as in %3s , will try to print the string in a width-3 field. But you then pass in List , which isn't a string, but rather is a list. That's okay, though, because Python knows how to print a list instance as a string. It's wider than 3 so Python prints it at whatever width it works out to. So Python prints something like this, complete with square brackets and commas:

[0, 4, 6, 9, 19, 19, 22, 25, 34, 41, 65, 71, 72, 74, 74, 75, 78, 79, 88, 99]

There are two easy ways to get the output you want. One is to use a for loop and print it one value at a time, like so:

for n in List:
    print("%3d" % n, end='')
print()

By using end='' we are telling Python not to print a "newline" after printing our number. Then, once the loop is done, we call print() by itself to print a newline.

The other easy way is to use the .join() method function to join together all the numbers you want to print, which will give you a single string that is exactly what you want to print. Then just print that!

s = ' '.join(str(n) for n in List)
print(s)

I don't know if you have seen anything like this before, but there is sort of a one-line mini loop inside the join() call. This is called a "generator expression" and it will generate the values we want. List contains integers, and join() needs strings, so we convert the integers to strings so join() knows what to do with them.

Of course we can do it all in one line if we like:

print(' '.join(str(n) for n in List))

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