简体   繁体   中英

Limiting user input in a list of integers in Python 3.x

I am new to Python and in one of my exercises I need to write a program that will store 5 integers entered to the console in a list, then print its length, type of the list, and print the sorted list.

So far, the most elegant way I could do it without limiting the input to 5 integers was:

a = [int(x) for x in input().split()]
print(len(a), type(a), sorted(a))

However, I can't get my head around how to add the command to store only 5 numbers entered by the user in the list and ignore the rest.

I thought of using int(input()) for x in range(5), but it didn't work, and I also don't know how to add the split then.

I know there is a way to store items in the list using map(), but I haven't come across that in my course yet, so if there is a simpler and more efficient way to do it with list(map()), I would highly appreciate if someone could guide me.

I only started learning, so any advice would be appreciated. Thanks!

You have two options:

  • Take the first five values from a line, ignore the rest
  • Check the length and tell the user to not enter so many values

The latter would give the user better feedback, where the first could lead to surprises ( What happened to the numbers at the end of my line? )

Ignoring the rest is easy; slice the list you create; the [:5] creates a new list with just (up to) 5 values:

a = [int(x) for x in input().split(maxsplit=5)[:5]]

The above also tells str.split() to only split up to 5 times, to avoid further work.

An error message should, by command-line tool convention, be written to sys.stderr and you would exit with a non-zero exit code:

a = [int(x) for x in input().split()]
if len(a) > 5:  # or len(a) != 5 if you must have exactly 5 values
    print('No more than 5 values, please!', file=sys.stderr)
    sys.exit(1)

When you use a library to handle command-line parsing, then the library usually includes a function to handle error communication and exit (such as argparse , where you'd use parser.error(message) to signal an issue and exit in one step).

Limit your split to the first 5 numbers via the maxsplit argument of str.split .

Then slice up to but not including the final element of the resultant list.

a = [int(x) for x in input().split(maxsplit=5)[:-1]]

Note you can also rewrite this with list + map :

a = list(map(int, input().split(maxsplit=5)[:-1]))

This will just keep the first 5 items in the list:

a = [int(x) for x in input().split()[:5]]

Using this gives all the items in the list that have index less than 5.

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