简体   繁体   English

获取多个用户输入的列表和地图之间的区别

[英]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

  1. The input() function returns the string '1 5 6 11 13' . input()函数返回字符串'1 5 6 11 13'
  2. Then, we call the .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.然而,这些仍然是字符串,我们想要整数。
  3. Finally, we apply 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 在此中创建更有效)案例而不是完整列表)
  4. If we want, we could cast that to a 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.

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