简体   繁体   English

将用户输入更改为列表中的 int 的更快方法?

[英]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() :您可以使用map()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地图(函数,*迭代)-> map object

Make an iterator that computes the function using arguments from each of the iterables.创建一个迭代器,使用来自每个可迭代对象的 arguments 计算 function。 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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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