简体   繁体   中英

Limiting number of input values in an array/list in Python

I'm obtaining input values in a list using the following statement:

ar = map(int, raw_input().split())

However, I would want to limit the number of inputs a user can give at a time. For instance, if the limit is specified by a number n, the array should only capture the first n values entered during the program.

eg: if n = 6, Input:

1 2 3 4 5 6 7 8 9 10

On performing 'print ar', it should display the following without any error messages:

[1, 2, 3, 4, 5, 6]

If you want to ignore the rest of the input, then you can use slicing to take only the first n input. Example -

n = 6
ar = map(int, raw_input().split(None, n)[:n])

We are also using the maxsplit option for str.split so that it only splits 6 times , and then takes the first 6 elements and converts them to int.

This is for a bit more performance. We can also do the simple - ar = map(int, raw_input().split())[:n] but it would be less performant than the above solution.

Demo -

>>> n = 6
>>> ar = map(int, raw_input().split(None, n)[:n])
1 2 3 4 5 6 7 8 9 0 1 2 3 4 6
>>> print ar
[1, 2, 3, 4, 5, 6]

How about indexing ar to just the 6th element? Technically, it's to the 7th element, as newarray will slice up to, but not including nth element

ar = map(int, raw_input().split())
print ar
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

newarray=ar[0:6]
print newarray
#[1, 2, 3, 4, 5, 6]

This should allow for unlimited input

I was looking for a solution to the same question.

I figured out what I can do below is my solution.

bookid = []
M = int(input())
S = input().split()
for i in range(M):
    books.append(S[i])
print(booksid)

But I think it's definitely not the most effective way to do it but easy.

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