简体   繁体   中英

Faster way to change user inputs into int in a list?

Currently, I have this code:

mylist = []
t1,t2 = input().split(' ')
t1 = int(t1)
t2 = int(t2)
mylist.append(t1)
mylist.append(t2)

Is there a more efficient way to do this?

In one line:

print([int(n) for n in input().split()])

Edit a previously created list

You can use map() and list.extend() :

my_list = []
my_list.extend(map(int, input().split()))  # .split(' ') can lead to unexpected behavior
print(my_list)
# >>> 123 132542
# [123, 132542]

map(func, *iterables) –> map object

Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.

This solution is resilient to multiple spaces between integers and can handle an undetermined amount of integers.

Create a new list:

my_list = list(map(int, input().split())

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