python - list(map(some code)) 和 map(some code) 没有区别
问题描述
def ask_for_two_floats(question):
"""
Asks user to input two floats separated by space bar. The input is asked
until user gives two suitable inputs. Inputs are returned as floats.
"""
while True:
try:
x, y = map(float, input(question).split())
except ValueError:
print("Please enter two floats separated by space. ")
continue
break
return x, y
print(ask_for_two_floats("Give me two numbers: "))
我的问题是,为什么很多人写列表(在地图功能前面?如果我写:
x, y = list(map(float, input(question).split()))
输出和函数的工作方式不会改变。输出始终是一个元组。那么,如果没有任何区别,为什么要在 list() 中编写 map 函数呢?如果我希望这个程序返回一个包含 x 和 y 的列表,如下所示:[x, y],我应该如何更改我的代码?
解决方案
对于第一个问题,您看不到差异的原因是您将map
对象解压缩为两个单独的变量。请注意,它map
返回的是生成器,而不是列表,因此转换为列表需要list()
.
例如,
>>> type(map(int, "123"))
<class 'map'>
>>> map(int, "123")
<map object at 0x00000203276D9C08>
>>> list(map(int, "123"))
[1, 2, 3]
>>> x, y, z = map(int, "123")
>>> x, y, z
(1, 2, 3)
>>> a, b, c = list(map(int, "123"))
>>> a, b, c
(1, 2, 3)
至于第二个问题,为了返回[x,y]
,只需在语句[x,y]
的地方写上。x,y
return
推荐阅读
- php - laravel 更新记录时的自定义验证规则
- java - 如何找出方法被执行?
- kentico - 为什么 Kentico 允许同时检查 Allow 和 Deny 页面权限
- php - 按 2 个分类法过滤帖子的功能
- rundeck - 在 Rundeck 3 中添加远程节点
- windows - 如何修复:找不到应用程序依赖项清单中指定的程序集:包:'System.Data.SqlClient'
- php - PHP 致命错误:不能在第 180 行 CENSORED 的数组中使用空数组元素
- ios - 在 iOS 中读取系统相机设置
- r - ggplot2中的柱形图使用分类变量作为填充
- r - 创建一个逻辑变量来标识组中两个日期时间之间的最小差异的行