简体   繁体   English

map 在 python 中如何工作?

[英]how does map works in python?

I am new to Python programming.我是 Python 编程的新手。 I encountered a way to take a list input using map.我遇到了一种使用 map 获取列表输入的方法。

code 1:代码 1:

l = list(map(int, input().split()))
print(l)

code 2:代码 2:

l = [map(int, input().split())]
print(l)

Both of them look identical to me,两个跟我长得一模一样

But when I took the input 1 2 3 4 , code #1 gave the output [1,2,3,4] and code #2 for the same input gave the output [<map object at 0x0000024DFD85F0C8>] .但是当我输入1 2 3 4时,代码 #1 给出了 output [1,2,3,4] ,相同输入的代码 #2 给出了 output [<map object at 0x0000024DFD85F0C8>]

What is the difference between both methods?这两种方法有什么区别? How are they different?它们有何不同? Any help is appreciated.任何帮助表示赞赏。

What list() does is it takes any iterable like generator, tuple, string, map etc. and exhousts given object to create list. list()的作用是它接受任何可迭代对象,如生成器、元组、字符串、map 等,并根据给定的 object 来创建列表。 For example:例如:

gen = (i**2 for i in range(10))  # -> <generator object <genexpr> at 0x7f5b7066e0f8>
list(gen)  # -> [0, 1, 4, 9]

tup = (1, 2, 3, 4)  # -> (1, 2, 3, 4)
list(tup)  # -> [1, 2, 3, 4]

str_ = '123'  # -> '123'
list(str_)  # -> ['1', '2', '3']

You can think of it as:你可以把它想象成:

def list(it):
    ret_list = []
    for el in it:
        ret_list.append(el)
    return el

Where as surrounding instances with [...] simply creates list with whatever you've passed, so:带有[...]的周围实例只是用您传递的任何内容创建列表,因此:

gen = (i**2 for i in range(10))  # -> <generator object <genexpr> at 0x7f5b7066e0f8>
[gen]  # -> [<generator object <genexpr> at 0x7f5b7066e0f8>]

tup = (1, 2, 3, 4)  # -> (1, 2, 3, 4)
[tup]  # -> [(1, 2, 3, 4)]

str_ = '123'  # -> '123'
[str_]  # -> ['123']

Naive implementation:天真的实现:

def brancets(*args):
    ret_list = []
    for arg in args:
        ret_list.append(arg)
    return ret_list

# [1, 2, 3] -> brackets(1, 2, 3)

The map() function executes a specified function for each item in a iterable. map() function 为可迭代对象中的每个项目执行指定的 function 。 The item is sent to the function as a parameter.该项目作为参数发送到 function。 you have to specify the function to execute in each item.您必须指定要在每个项目中执行的 function。 to display the final result you can use "list" for readability this is an example:要显示最终结果,您可以使用“列表”以提高可读性,这是一个示例:

def myfunc(a, b):
   return a + b

x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))
print(x)
print(list(x)) #for readability 

in your case you can do this在你的情况下你可以这样做

def myfunc(a)
   return int(a)*2
x = map(myfunc,input().split())
print (list(x)) 

check this link: https://www.w3schools.com/python/ref_func_map.asp检查此链接: https://www.w3schools.com/python/ref_func_map.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM