【问题标题】:Combining two lists into a dictionary in python [duplicate]在python中将两个列表组合成字典[重复]
【发布时间】:2014-10-09 02:13:09
【问题描述】:

例如,如果我有两个列表:

listA = [1, 2, 3, 4, 5]
listB = [red, blue, orange, black, grey]

我试图弄清楚如何在两列中显示两个参数列表中的元素, 分配1: red, 2: blue...等等。

这必须在不使用内置zip函数的情况下完成。

【问题讨论】:

  • 查看zip函数
  • @stanleyxu2005,我错过了关于dict 的内容吗?为什么你和其他两个答案在这里使用dict
  • @gnibbler 哦,你是对的。他的代表1: red, 2:blue 误导我创建一个字典。他还希望在不使用zip 的情况下解决问题。这似乎是一个家庭作业问题......

标签: python list dictionary


【解决方案1】:
 >>> listA = [1, 2, 3, 4, 5]
 >>> listB = ["red", "blue", "orange", "black", "grey"]
 >>> dict(zip(listA, listB))
 {1: 'red', 2: 'blue', 3: 'orange', 4: 'black', 5: 'grey'}

【讨论】:

  • 很遗憾,我的老师不希望我们使用“zip”,因为我们还没有研究过。
  • -1 你的老师。阻止学生提前阅读不是教学。
  • 你为什么要转换成dictdict 的打印顺序无法保证。
  • 对于那些对性能感兴趣的人,似乎zip 方法比在简单的for 循环中执行此任务要慢。在我的测试中,for 循环方法的速度是zip 方法的两倍,尽管zip 方法读起来更优雅。
【解决方案2】:

如果不能使用 zip,请执行 for 循环。

d = {} #Dictionary

listA = [1, 2, 3, 4, 5]
listB = ["red", "blue", "orange", "black", "grey"]

for index in range(min(len(listA),len(listB))):
    # for index number in the length of smallest list
    d[listA[index]] = listB[index]
    # add the value of listA at that place to the dictionary with value of listB

print (d) #Not sure of your Python version, so I've put d in parentheses

【讨论】:

    【解决方案3】:

    特教版:

    list_a = [1, 2, 3, 4, 5]
    list_b = ["red", "blue", "orange", "black", "grey"]
    
    for i in range(min(len(list_a), len(list_b))):
        print list_a[i], list_b[i]
    

    【讨论】:

      【解决方案4】:

      我怀疑你的老师想让你写类似的东西

      for i in range(len(listA)):
          print listA[i], listB[i]
      

      然而,这在 Python 中是可憎的。

      这是不使用zip的一种方法

      >>> listA = [1, 2, 3, 4, 5]
      >>> listB = ["red", "blue", "orange", "black", "grey"]
      >>> 
      >>> b_iter = iter(listB)
      >>> 
      >>> for item in listA:
      ...     print item, next(b_iter)
      ... 
      1 red
      2 blue
      3 orange
      4 black
      5 grey
      

      但是zip 是解决这个问题的自然方法,你的老师应该教你这样想

      【讨论】:

        【解决方案5】:

        通常,zip 是解决问题的最佳方式。但由于这是一个家庭作业,而且你的老师不允许你使用zip,我想你可以从这个页面上采取任何解决方案。

        我提供了一个使用 lambda 函数的版本。请注意,如果两个列表的长度不相同,则会在相应的位置打印一个None

        >>> list_a = [1, 2, 3, 4, 5]
        >>> list_b = ["red", "blue", "orange", "black", "grey"]
        >>> for a,b in map(lambda a,b : (a,b), list_a, list_b):
        ...     print a,b
        ... 
        1 red
        2 blue
        3 orange
        4 black
        5 grey
        

        【讨论】:

          猜你喜欢
          • 2011-11-08
          • 1970-01-01
          • 2018-10-14
          • 2018-10-05
          • 1970-01-01
          • 2020-03-03
          • 2019-01-05
          • 1970-01-01
          • 2017-04-16
          相关资源
          最近更新 更多