Python 3中`map`函数的`int`参数是什么意思?

3
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())

在上面的代码中,map函数接受两个参数,我理解第二个参数是干什么用的,但是不明白'int'参数的作用。

3
你看过文件吗?有哪个部分让你不理解? - Aran-Fey
3
你是认真的吗? - Ignacio Vazquez-Abrams
是的,我已经阅读了文档和许多其他资源,但在map函数中我没有得到'int'参数。这有什么用?@Aran-Fey - Prathamesh More
@IgnacioVazquez-Abrams 谢谢您提供的文档链接。我有了一些想法! - Prathamesh More
2个回答

4
  • map(function, iterable):返回一个迭代器,该迭代器将iterable中的每个元素应用于function,并产生结果。
  • int(x):将数字或字符串x构造为整数对象。

因此,它将返回一个可迭代对象,在该对象上将 int() 函数应用于来自 .split() 的每个子字符串,这意味着它将每个子字符串转换为 int 。

示例:

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")]

使用自定义函数而不是 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]

哦!这个字符串将被转换为整数! - Prathamesh More
2
分割将其分解,int将每个位转换为整数,是的。 - Zev

3
假设我在第一个提示框中输入5并按回车键:
n = int(input())

将输入的“5”转换为整数5。因此,我们从string转换为int
然后,我们将获得另一个输入提示,因为我们在下一行再次使用了input():这次我会输入123 324 541 123 134,然后按回车键。 .split()将其拆分成“123”,“324”,“541”,“123”,“134”,这是一个字符串的列表(也是一个map)。然后,我们将int映射到它们上面,以便得到一个intmap而不是字符串。 int将字符串转换为整数。
在查看代码时,尝试在REPL(read execute print, looper)中尝试一些内容通常很有帮助。在命令提示符中,只需输入pythonpython3(如果已安装)或使用replt.it。输入a = "123" + "321",然后尝试`a = int("123") + int("321")
将其包装在list(map(int, input().split()))中,以获取list而不是map

这是一个完美的解释!现在,我如何访问arr列表的第一个元素?@Zev - Prathamesh More
当我尝试访问arr列表的第一个元素时,出现了错误。 ~if name == 'main': n = int(input()) arr = map(int, input().split())save = 0; smallNumber = arr[0]~ - Prathamesh More
arr[0] is not working. smallNumber = arr[0] TypeError: 'map' object is not subscriptable - Prathamesh More
你需要在它周围加上list(),这样它就不是一个映射而是一个列表。 - Zev
哦!明白了!谢谢! - Prathamesh More

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接