【问题标题】:split function and integers in python 3.7python 3.7中的拆分函数和整数
【发布时间】:2018-07-14 08:50:04
【问题描述】:

以下是以下代码:

a = list(map(int, input().split()))
b = list(map(int, input().split()))

上面的代码可以正常工作,但是下面的代码会报错。你能解释一下吗?

l = input()
i = int(l.split())
m = input()
j = int(m.split())

类型错误是:int() 参数必须是字符串、类似字节的对象或数字,而不是 'list. 我想弄清楚上面的代码部分是如何工作的,而不是低于一个。

【问题讨论】:

  • 请同时发布错误。
  • map(int,input().split()) 和 int(input().split()) 有什么不同
  • map()在哪里?
  • 先生,我没听明白。你的意思是 map(int,input().split()) 还是别的什么?
  • 即使我使用 int(str(input().split()) 它仍然会抛出一个错误。那么 map(int,input().split()) 与 int(input ().split())

标签: python-3.x split int map-function


【解决方案1】:

split 返回一个字符串数组,正如您所见,int 不能将其作为参数。 map 接受一个函数引用(在本例中为int)并将其应用于可迭代对象的每个成员,从而将所有字符串转换为整数。

【讨论】:

  • 所以主要区别是 int 尝试应用整个字符串,而 map 将它应用到列表的各个元素。好的,谢谢。
  • 先生,python 中的字符串是可迭代的,对吧?那么写map(int,"string")是否有效。您如何证明上述行为的合理性,因为它在语法上是正确的但不会产生任何输出!
  • @Mahantesh map 如何将int 应用于这些非整数值?它确实提供了输出。在 Python 3 中 map 是“惰性”的,它只会在使用时应用函数:action = map(int, 'string') ; list(action) ;Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 's'
  • 先生,我是初学者,请您解释一下“懒惰”这个词吗?
  • @Mahantesh 在示例map(int,"string") 中,map 尝试迭代字符串的每个字符,然后失败,因为它无法将第一个字符 (s) 转换为 int。跨度>
猜你喜欢
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多