什么时候应该使用字典、列表或集合?

是否存在更适合每种数据类型的场景?


当前回答

虽然这里不包括集合,但它很好地解释了字典和列表:

Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names. Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book.

http://www.sthurlow.com/python/lesson06/

其他回答

与列表、字典和集合相结合,还有另一个有趣的python对象OrderedDicts。

有序字典就像普通字典一样,但是它们会记住条目插入的顺序。在有序字典上迭代时,项将按照键第一次添加的顺序返回。

OrderedDicts在需要保留键的顺序时可能很有用,例如处理文档:通常需要文档中所有术语的向量表示。因此,使用OrderedDicts,您可以有效地验证一个项之前是否已读取,添加项,提取项,在所有操作之后,您可以提取它们的有序向量表示。

在使用它们的时候,我为它们的方法做了一个详尽的备忘单,供你参考:

class ContainerMethods:
    def __init__(self):
        self.list_methods_11 = {
                    'Add':{'append','extend','insert'},
                    'Subtract':{'pop','remove'},
                    'Sort':{'reverse', 'sort'},
                    'Search':{'count', 'index'},
                    'Entire':{'clear','copy'},
                            }
        self.tuple_methods_2 = {'Search':'count','index'}

        self.dict_methods_11 = {
                    'Views':{'keys', 'values', 'items'},
                    'Add':{'update'},
                    'Subtract':{'pop', 'popitem',},
                    'Extract':{'get','setdefault',},
                    'Entire':{ 'clear', 'copy','fromkeys'},
                            }
        self.set_methods_17 ={
                    'Add':{['add', 'update'],['difference_update','symmetric_difference_update','intersection_update']},
                    'Subtract':{'pop', 'remove','discard'},
                    'Relation':{'isdisjoint', 'issubset', 'issuperset'},
                    'operation':{'union' 'intersection','difference', 'symmetric_difference'}
                    'Entire':{'clear', 'copy'}}

字典:当你想用索引以外的东西来查找某个东西时。例子:

dictionary_of_transport = {
    "cars": 8,
    "boats": 2,
    "planes": 0
}
print("I have the following amount of planes:")
print(dictionary_of_transport["planes"])
#Output: 0

列表和集:当您想要添加和删除值时。 列表:使用索引查找值 集:存储值,但不能使用任何方法访问它们。

简而言之,使用:

列表-如果你需要一个有序的项目序列。

Dict -如果你需要将值与键联系起来

设置—如果您需要保留唯一的元素。

详细解释

List

列表是一个可变序列,通常用于存储同构项的集合。

列表实现了所有常见的序列操作:

X在l里和X不在l里 L [i], L [i:j], L [i:j:k] Len (l) min(l) max(l) l.count (x) l.index(x[, i[, j]]) - x在l中第一次出现的索引(在i前后和j索引之前)

list还实现了所有可变序列操作:

l[i] = x - item i of l is replaced by x l[i:j] = t - slice of l from i to j is replaced by the contents of the iterable t del l[i:j] - same as l[i:j] = [] l[i:j:k] = t - the elements of l[i:j:k] are replaced by those of t del l[i:j:k] - removes the elements of s[i:j:k] from the list l.append(x) - appends x to the end of the sequence l.clear() - removes all items from l (same as del l[:]) l.copy() - creates a shallow copy of l (same as l[:]) l.extend(t) or l += t - extends l with the contents of t l *= n - updates l with its contents repeated n times l.insert(i, x) - inserts x into l at the index given by i l.pop([i]) - retrieves the item at i and also removes it from l l.remove(x) - remove the first item from l where l[i] is equal to x l.reverse() - reverses the items of l in place

可以利用append和pop方法将列表用作堆栈。

字典

字典将可哈希值映射到任意对象。字典是一个可变对象。字典的主要操作是存储带有某个键的值,并在给定键的情况下提取值。

在字典中,不能使用不可哈希的值作为键,即包含列表、字典或其他可变类型的值。

Set

set是不同哈希对象的无序集合。集合通常用于包括成员测试,从序列中删除重复项,以及计算数学操作,如交集、并集、差分和对称差分。

当您有一组映射到值的唯一键时,请使用字典。 如果你有一个有序的项目集合,可以使用列表。 使用集合存储一组无序的项。