如何在 help() 中搜索未知函数?

How to search for unknown functions in help()?

有时我正在寻找一个函数,但我不知道它的名字,甚至不知道它是否存在。我遇到了一个问题,我需要对字符串进行排序。最终在本论坛某人的推荐下使用的函数是函数'sorted'。

当我输入 help(lst) 时,我找到函数 L.sort(key = None, reverse = False)

但函数 sorted() 在我的情况下会更容易使用。

所以我有两个问题:

  1. sorted()是什么类型的函数,L.sort()是什么类型的函数。我知道功能差异,但我想知道功能的名称类型。 L.sort() 用于列表,所以我想有一个函数名称,用于特定类型的对象。而sorted()在IDLE中变成了一个紫色的字,所以我认为它是某种特殊类型的函数。

  2. 如何找到像紫色函数 sorted() 这样的函数。如果我知道如何以有效的方式使用 IDLE 中的帮助功能,它会使编程变得更容易一些。有"purple functions"的列表吗?

我试图 google 此信息,但我找不到真正有用的答案。

提前致谢,

1..sort()sorted()的主要区别如下:

  • sorted() returns 一个 new 排序列表,原始列表不受影响。
  • list.sort() 对列表 就地 进行排序,改变列表索引,并且 returns None (就像所有就地操作一样).

查看文档here


2。在您的控制台中输入 python 后使用:

dir(__builtins__)

这将打印大部分内置 python 函数,包括 sorted()


无论如何,如果您想找到专门针对 lists 的内置 python 函数,那么只需 google。您会发现这样的页面:https://docs.python.org/3/tutorial/datastructures.html

免责声明 下面提到的资源和工具集合并未声称是完整的,我可能无意中错过或跳过了其他很棒的文档或项目。如果您认为缺少某些内容,请随时添加到列表中(我将文档资源主要限制为 Python 内部文档,因为我认为这应该是每个搜索路径的第一站)。


如何查找有关 Python 及其生态系统的信息

您可以搜索Python documentation directly: e.g. searching for "sort list" gives list.sort as the top result where you'll also find a hint about sorted. Another effective way to search the Python docs is via your favorite search engine and limiting the search results: e.g. sort list site:docs.python.org (Google), which will eventually lead to the Sorting HOW TO。 Whosebug 当然是另一个值得考虑的重要资源,尤其是在超越基础知识时。

以下是其他 Python 资源的(非详尽)列表,您可以在其中找到很多有用的信息(排名不分先后):

现在有很多信息需要消化,可能有点让人不知所措,但几乎所有的搜索功能都能满足您的需求:您可以直接搜索资源,也可以直接点击浏览器的搜索栏,或者您也可以转到您最喜欢的搜索引擎并将结果限制为这些页面(之一)。然后你就可以开始了,你将在途中学到大部分东西!

解释器中的可发现性

您可以在任何对象上广泛使用 dirhelp 以了解您可以用它们做什么(尝试 dir(dir)help(help))。 Python 解释器也支持 TAB 补全,所以输入 sort<TAB> 会在解释器中得到 sorted(builtinssorted 是其中之一)在每个会话中都可用,您可以通过导入 builtins:

查看可用的内容
>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TargetScopeError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

要获得更好的输出格式,您可以使用 pprint.pprint(标准库的一个函数):

>>> from pprint import pprint
>>> pprint(dir(builtins))
# Here it will print the results line-by-line.

Python的help()界面

只需在解释器中键入 help,您就会进入一个专用的帮助界面,该界面允许获取各种信息:

>>> help()

Welcome to Python 3.7's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

如帮助文本所示,例如,我们可以获得所有可用模块的列表,这些模块可以通过 help> modules 进行 import;特定模块的更多信息:例如help> datetime(这将分页输出)。在浏览 help() 界面时,您会发现有关如何使用它以及如何搜索 Python 的更多提示。感受它的最好方法是开始并试验它。

高级口译员:IPython

现在有一些其他 Python 解释器(除了标准解释器)提供了增强的可用性。其中 IPython is quite popular. You can use it like the standard interpreter and it also has lots of features for advanced usability (too many to be covered here, but the documentation 涵盖了您)。参考你的例子:

In [1]: sorted  # here you can use TAB completion at any point
Out[1]: <function sorted(iterable, /, *, key=None, reverse=False)>

In [2]: sorted?  # "?" gives you an overview of the docs
Signature: sorted(iterable, /, *, key=None, reverse=False)
Docstring:
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
Type:      builtin_function_or_method

In [3]: list.sort?  # TAB completion also works here
Docstring: L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
Type:      method_descriptor

IPython 在您的浏览器中:Jupyter

现在在 IPython 之上还有另一个受欢迎的项目,Jupyter 及其 "Jupyter Notebooks"。它们类似于 IPython 但使用浏览器作为前端(而不是命令行)并且它在 IPython 之上具有更多功能(它与 IPython 内核通信背景,所以它实际上只是另一个前端);我强烈建议您检查一下 - 它非常适合进行实验和快速了解该语言,但也适合更高级的 "interactive" 使用 Python (例如,这在数据科学中很常见)。这是屏幕截图:

原题:sorted vs list.sort

sorted 是一个内置函数,它可用于对任何可迭代对象(不仅是列表)进行排序,输出将是一个排序列表:

>>> import builtins
>>> sorted is builtins.sorted
True
>>> sorted([3, 1, 2])
[1, 2, 3]
>>> sorted(range(5, 0, -1))
[1, 2, 3, 4, 5]
>>> sorted(dict(b='foo', c='bar', d='baz'), reverse=True)
['d', 'c', 'b']
>>> sorted(dict(b='foo', c='bar', d='baz').items(), key=lambda x: x[1])
[('c', 'bar'), ('d', 'baz'), ('b', 'foo')]
另一方面,

list.sortlist class 的一种方法,并在 [=39] 的实例上 就地 操作=]:

>>> l = [3, 2, 1]
>>> l.sort()
>>> l
[1, 2, 3]
>>> list.sort(l, reverse=True)  # this also works.
>>> l
[3, 2, 1]
>>> list.sort(dict(a='foo', b='bar'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'sort' requires a 'list' object but received a 'dict'