【问题标题】:the difference between list and dictionary in pythonpython中列表和字典的区别
【发布时间】:2021-12-09 01:26:15
【问题描述】:

代码 A:

t1 = {}

t1[0] = -5

t1[1] = 10.5

代码 B:

t2 = []

t2[0] = -5

t2[1] = 10.5

为什么代码B有“IndexError: list assignment index out of range”以及如何解决?

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    字典是哈希集。它们将任意(可散列的)键与值配对,并且不期望这些键是连续的,甚至实际上是 数字

    replacement_dict = {'old_name': 'new_name'}  # you could use this to implement a find/replace
    

    相比之下,列表是密集的,它们的索引(不是键——这是一个不同的术语,使用object[index] 表示法以相同的方式访问)是数字。因此,您不能只访问大于列表长度的随机值,而必须使用append

    lst = []
    lst[0] = 'blah'  # throws an IndexError because len(lst) is 0
    
    lst.append('blah')
    assert lst[0] == 'blah
    

    【讨论】:

      【解决方案2】:

      字典的工作方式类似于键值对。每次在字典中分配新值时,都会创建一个新的键值对。

      列表就像一个可以随意扩展的数组,但是如果您尝试访问超过其当前大小的索引,它将返回错误。您通常使用 t2.append(value) 扩展列表。

      【讨论】:

        【解决方案3】:

        字典允许分配尚不存在的元素。列表没有。这就是它们的设计方式。

        您可以通过两种方式解决此问题。首先是将列表初始化为所需的大小:

        t2 = [None]*2
        

        第二种是调用append而不是使用=

        t2 = []
        t2.append(-5)
        t2.append(10.5)
        

        【讨论】:

          【解决方案4】:

          字典存储带有名称值的数据。

          dictionary = {"name": "value"}
          
          print(dictionary["name"])
          
          # Prints "value".
          

          列表存储一系列值。这些值没有任何名称,它们是通过索引访问的。

          list = ["value", "other value"]
          
          print(list[0])
          
          # Prints "value".
          

          要解决您的问题,请使用append

          t2 = []
          
          t2.append(-5)
          
          t2.append(10.5)
          

          【讨论】:

            猜你喜欢
            • 2017-09-23
            • 1970-01-01
            • 2020-12-24
            • 2016-08-16
            • 2017-12-30
            • 2022-01-25
            • 2012-10-15
            • 2019-03-22
            • 1970-01-01
            相关资源
            最近更新 更多