[英]What does `int` parameter in `map` function of Python 3?
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
In the above code, map function taking two parameters, I got the understanding of the second parameter what it does but I am not getting 'int' parameter.在上面的代码中,map 函数采用两个参数,我了解了第二个参数的作用,但没有得到 'int' 参数。
Therefore, it will return an iterable where it applied the int() function to each substring from .split()
, meaning it casts every substring to int.因此,它将返回一个可迭代对象,它将 int() 函数应用于.split()
每个子字符串,这意味着它将每个子字符串转换为 int。
Example:例子:
arr = map(int, "12 34 56".split())
arr = list(arr) # to convert the iterable to a list
print(arr) # prints: [12, 34, 56]
# This is equivalent:
arr = [int("12"), int("34"), int("56")]
Other example with custom function instead of int() :使用自定义函数代替int() 的其他示例:
def increment(x):
return x + 1
arr = map(increment, [1, 2, 3, 4, 5])
arr = list(arr)
print(arr) # prints: [2, 3, 4, 5, 6]
Let's say I type 5
and then enter at the first prompt:假设我输入5
然后在第一个提示处输入:
n = int(input())
Would take the input "5" and make it into the integer 5
.将输入 "5" 并将其转换为整数5
。 So we are going from a string
to an int
所以我们从一个string
到一个int
Then we will get another input prompt because we have input() again in the next line: This time I'll type 123 324 541 123 134
and then enter.然后我们将得到另一个输入提示,因为我们在下一行再次输入了 input(): 这次我将输入123 324 541 123 134
然后输入。
the .split()
will split this into "123", "324", "541", "123", "134" which is a list (well a map
) of strings. .split()
会将其拆分为“123”、“324”、“541”、“123”、“134”,这是一个字符串列表(以及map
)。 Then we'll map int
onto them to give ourselves a map
of int
s rather than strings.然后我们将int
映射到它们上,为我们自己提供一个int
而不是字符串的map
。 int
converts the strings to integers. int
将字符串转换为整数。
When checking out code it is often helpful to try things in a REPL (read execute print, looper).在检查代码时,在 REPL(读取执行打印、looper)中尝试通常会很有帮助。 In your command promt just type python
or python3
if you have it installed or use replt.it .在您的命令 promt 中,如果您安装了python
或python3
或使用replt.it ,只需键入它。 Type a = "123" + "321"
then try `a = int("123") + int("321")输入a = "123" + "321"
然后尝试 `a = int("123") + int("321")
Wrap this with list(map(int, input().split())) to get a list
rather than a map
.用 list(map(int, input().split())) 包装它以获取list
而不是map
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.