简体   繁体   English

函数返回中的map与list理解

[英]map versus list comprehension in function return

Simple question: 简单的问题:

Matplotlib has a function that returns two values: Matplotlib有一个返回两个值的函数:

locs,label = plt.yticks()

Pylint complains about this line, telling me "Used builtin function map". Pylint抱怨此行,并告诉我“已使用的内置函数映射”。 So I went to pylint site and found this: http://pylint-messages.wikidot.com/messages:w0141 So, I'm trying to fix this warning using list comprehension. 因此,我去了pylint网站,发现了这一点: http ://pylint-messages.wikidot.com/messages:w0141因此,我正在尝试使用列表理解来解决此警告。 But what is the correct form? 但是正确的形式是什么?

[(locs,label) for plt.yticks()]

is not working. 不管用。

Thanks! 谢谢!

EDIT: I made a simple test script to try to show the problem, and the problem was one line below: 编辑:我做了一个简单的测试脚本,以尝试显示该问题,而问题是下面的一行:

#!/usr/bin/python

""" docstring """

import matplotlib.pyplot as plt

LOCS, LABEL = plt.yticks()

plt.yticks(LOCS, map(lambda x: "%.2f" % x, LOCS)) # offending line

print(LOCS)

So duh, I was looking on the wrong line. 所以,我在错误的路线上寻找。 How this lambda can be adjusted to list comprehension? 如何调整此lambda以列出理解? Thanks 谢谢

locs,label = plt.yticks()

Is the correct way to receive two variables from a function. 是从函数接收两个变量的正确方法。 You could receive it as a single variable, and work with the tuple object, but that would be pointless. 您可以将其作为单个变量接收,并使用元组对象,但这将毫无意义。

It's possible that pylint is complaining about plt.yticks . pylint可能在抱怨plt.yticks Apart from it being out of your control, it is not in general preferable to use a list comprehension instead of map , just in a wide variety of cases. 除了它是你无法控制的,它不是一般最好使用列表理解,而不是map ,只是在各种情况下。

In the case of plt.yticks(LOCS, map(lambda x: "%.2f" % x, LOCS)) , a list comprehension is likely to be more readable, and may be faster. plt.yticks(LOCS, map(lambda x: "%.2f" % x, LOCS)) ,列表理解可能更易读,并且可能更快。

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

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