python中括号的不同含义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30700603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:50:52  来源:igfitidea点击:

different meanings of brackets in python

pythonbrackets

提问by jake wong

I am curious, what do the 3 different brackets mean in python programming? Not sure if i'm correct about this, but please correct me if i'm wrong.

我很好奇,python 编程中 3 个不同的括号是什么意思?不确定我是否正确,但如果我错了,请纠正我。

[] - # Normally used for dictionaries, list items
() - # Used to identify params
{} - # I have no idea what this does... 

Or if these brackets can be used for other purposes, any advises are welcomed! Thanks!

或者如果这些括号可以用于其他目的,欢迎任何建议!谢谢!

采纳答案by Maltysen

  • []: Used to define mutable data types - lists, list comprehensions and for indexing/lookup/slicing.
  • (): Define tuples, order of operations, generator expressions, function calls and other syntax.
  • {}: The two hash table types - dictionaries and sets.
  • []:用于定义可变数据类型 - 列表、列表推导式和用于索引/查找/切片。
  • ():定义元组、操作顺序、生成器表达式、函数调用和其他语法。
  • {}: 两种哈希表类型 - 字典和集合。

回答by Rampant

() parentheses are used for order of operations, or order of evaluation, and are referred to as tuples. [] brackets are used for lists. List contents can be changed, unlike tuplecontent. {} are used to define a dictionary in a "list" called a literal.

() 括号用于操作顺序或求值顺序,称为元组。[] 括号用于列表。与元组内容不同,列表内容可以更改。{} 用于在称为文字的“列表”中定义字典

回答by ttq

In addition to Maltysen's answer and for future readers: you can define the []and ()operators in a class, by defining the class methods:

除了 Maltysen 的回答以及对于未来的读者:您可以通过定义类方法在类中定义[]()运算符:

An example is numpy.mgrid[...]. In this way you can define it on your custom-made objects for any purpose you like.

一个例子是numpy.mgrid[...]。通过这种方式,您可以出于您喜欢的任何目的在自定义对象上定义它。