【问题标题】:Insert arrays into a dictionary [closed]将数组插入字典[关闭]
【发布时间】:2021-08-16 04:44:00
【问题描述】:

我有 3 个数组:

id_ = [1,2,3,4]
names = ['Mark', 'Fred', 'Justin', 'Tim']
Jobs = ['Teacher', 'doctor', 'Coach', 'Fireman']

我想使用for 循环将它们插入字典中,以得到类似这样的内容:

 {1: ('Mark', 'Teacher'), 2: ('Fred', 'doctor'), 3: ('Justin', 'Coach'), 4: ('Tim', 'Fireman')}

我该怎么做?

【问题讨论】:

    标签: python arrays dictionary


    【解决方案1】:

    如果您将列表压缩在一起,则可以遍历它们,添加 dict 条目和 i:(n, j)。

    id_ = [1,2,3,4]
    names = ['Mark', 'Fred', 'Justin', 'Tim']
    Jobs = ['Teacher', 'doctor', 'Coach', 'Fireman']
    
    print({i : (n, j) for i, n, j in zip(id_, names, Jobs)})
    

    输出:

    {1: ('Mark', 'Teacher'), 2: ('Fred', 'doctor'), 3: ('Justin', 'Coach'), 4: ('Tim', 'Fireman')}
    

    【讨论】:

      【解决方案2】:

      这将为每个名称添加一个编号的(名称,工作)对:

      dict = {}
      i = 0 # or 1, if you prefer. but it's not proper to start a list from 1 when programming.
      while i < len(names):
          dict[i] = (names[i], Jobs[i])
          i = i+1
      

      作为一个for循环:

      for i in id_:
          dict[i] = (names[i-1], Jobs[i-1])
      

      但我更喜欢第一种方法,因为它不需要先列出数字。这也比 zip 函数更具可读性。我必须对每个都做一个 -1 才能使计数起作用,因为他从 1 开始编号。

      【讨论】:

      • 这不是for 循环
      • 不,因为这不是正确的做法。我的方法更好,因为它不需要预先制作数字列表。
      • @yes 1) 发帖人要求使用for 循环; 2) for 循环不需要预先制作数字列表(例如,range(x) 是一个生成器)
      • @Woodford 是的,但是世界上怎么这么好。不再争论。
      【解决方案3】:
      >>> id_ = [1,2,3,4]
      >>> names = ['Mark', 'Fred', 'Justin', 'Tim']
      >>> Jobs = ['Teacher', 'doctor', 'Coach', 'Fireman']
      
      >>> dict(zip(id_, zip(names, Jobs)))
      {1: ('Mark', 'Teacher'), 2: ('Fred', 'doctor'), 3: ('Justin', 'Coach'), 4: ('Tim', 'Fireman')}
      

      文档:

      【讨论】:

        猜你喜欢
        • 2021-10-27
        • 2021-08-07
        • 1970-01-01
        • 1970-01-01
        • 2021-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多