首页 > 解决方案 > 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],我应该如何更改我的代码?

标签: pythonpython-3.x

解决方案


对于第一个问题,您看不到差异的原因是您将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,yreturn


推荐阅读