列表、元组、集合和字典有什么区别?

2022-01-17 00:00:00 python list dictionary set tuples

问题描述

我对列表、元组、集合和字典感到困惑,有人给我明确的想法.给我你理解的差异不要给教科书定义.

I have confused with lists, tuples, sets and dictionaries someone give me clear cut idea. Give me the difference from your understanding don't give the text book definitions.


解决方案

列表是按特定顺序排列的元素序列.您可以访问具有数字索引的元素,例如the_list[3].测试列表是否包含元素等几个操作所花费的时间是 O(n),即与列表的长度成正比.

A list is a sequence of elements in a specific order. You can access elements with a numerical index, e.g. the_list[3]. The time taken for several operations such as testing if the list contains an element is O(n), i.e. proportional to the length of the list.

元组基本上是一个不可变的列表,这意味着您不能添加、删除或替换任何元素.

A tuple is basically an immutable list, meaning you can't add, remove, or replace any elements.

集合没有顺序,但与列表相比具有优势,即测试集合是否包含元素要快得多,几乎与集合的大小无关.它还有一些方便的操作,例如并集和交集.

A set has no order, but has the advantage over a list that testing if the set contains an element is much faster, almost regardless of the size of the set. It also has some handy operations such as union and intersection.

字典是从键到值的映射,其中键可以是各种不同的对象,而列表中的键"只能是数字.所以你可以有 the_dict = {'abc': 3, 'def': 8} 然后 the_dict['abc']3.它们的 dict 键很像一个集合:它们没有顺序,您可以快速测试它们的存在.

A dictionary is a mapping from keys to values where the keys can be all sorts of different objects, in contrast to lists where the 'keys' can only be numbers. So you can have the_dict = {'abc': 3, 'def': 8} and then the_dict['abc'] is 3. They keys of a dict are much like a set: they have no order and you can test for their existence quickly.

集合的元素和字典的键必须是可散列的.数字、字符串、元组和许多其他东西都是可散列的.列表、集合和字典不可散列.

The elements of a set and the keys of a dict must be hashable. Numbers, strings, tuples, and many other things are hashable. Lists, sets, and dicts are not hashable.

相关文章