定义变量(Python)时,[ ] 和 { } 有什么区别?

What's the difference between [ ] and { } when defining a variable (Python)?

我看到别人用

CurlyBraces = {'Lorem','Ipsum'}

用于他们在 python 中的表格,但其他一些人使用

SquareBrackets = ['Lorem','Ipsum']

他们的桌子有什么区别?

花括号创建一个集合 (https://www.w3schools.com/python/python_sets.asp) or Dictionary, while square braces creates List (https://www.w3schools.com/python/python_lists.asp)。

集合是一种无序数据结构,最适合快速查找项目,而列表是一种有序数据结构

第一个是shorthand set,第二个是list。您也可以使用与第一个非常相似的方法来定义 dict.

例如,这里有 2 个等效定义:

# list
my_list_1 = [1, 2, "cat"]

my_list_2 = list()
my_list_2.append(1)
my_list_2.append(2)
my_list_2.append("cat")


# set
my_set_1 = {1, 2, "cat"}

my_set_2.add(1)
my_set_2.add(2)
my_set_2.add("cat")


# dict
my_dict_1 = {"animal": "cat", 42: "number", "something": 1}

my_dict_2["animal"] = "cat"
my_dict_2[42] = "number"
my_dict_2["something"] = 1

另请注意,如果您看到 some_var = {},则表示 dict。套装在 Python.

中更为罕见