[英]Difference between list and map for getting multiple user inputs
从用户获取多个输入的list(int(input()).split())
和map(int,input().split())
之间有什么区别?
Let's examine them closely:让我们仔细检查它们:
list(int(input()).split())
expands into list(int(input()).split())
扩展为
list( # Make a list out of...
int( # the value of...
input() # input from the user,
) # converted to an integer.
.split() # Then, split that.
)
This doesn't make sense.这没有意义。 Say you input something like
15
.假设您输入了类似
15
。 The input()
function returns the string '15'
, which gets converted into the integer 15
. input()
函数返回字符串'15'
,该字符串被转换为整数15
。 Integers don't have a .split()
operation, so you get a SyntaxError
.整数没有
.split()
操作,所以你会得到一个SyntaxError
。
Now, let's look at map(int,input().split())
:现在,让我们看看
map(int,input().split())
:
map( # Apply the function...
int # (that is, `int()`)
, # ...to every element in the iterable...
input() # (First, take the input from the user,
.split() # and then split it)
) # ...and return all that as a list
This time, we input something like 1 5 6 11 13
.这次,我们输入类似
1 5 6 11 13
。
input()
function returns the string '1 5 6 11 13'
. input()
函数返回字符串'1 5 6 11 13'
。.split()
function on that string, which returns a list of substrings that were separated by whitespace - that is, it returns the list ['1', '5', '6', '11', '13']
..split()
函数,该函数返回由空格分隔的子字符串列表 - 也就是说,它返回列表['1', '5', '6', '11', '13']
。 These are still strings, though, and we want integers.int()
to every element of that list, which gets us the end result [1, 5, 6, 11, 13]
, except it's in a map
data structure (which is more efficient for python to create in this case than a full list)int()
应用于该列表的每个元素,这为我们提供了最终结果[1, 5, 6, 11, 13]
,除了它在map
数据结构中(这对于 python 在此中创建更有效)案例而不是完整列表)list
to use it easily - that would just be enclosing that entire expression in list(...)
.list
以轻松使用它——这只是将整个表达式包含在list(...)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.