Combining two lists into a dictionary in python
本问题已经有最佳答案,请猛点这里访问。
例如,如果我有两个列表:
1 2 | listA = [1, 2, 3, 4, 5] listB = [red, blue, orange, black, grey] |
我想知道如何在两列中显示两个参数列表中的元素,分配
这必须在不使用内置
1 2 3 4 | >>> 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'} |
如果你不能用拉链,做一个for循环。
1 2 3 4 5 6 7 8 9 10 11 | 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 |
特别教师版:
1 2 3 4 5 | 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] |
我怀疑你的老师想让你写点什么
1 2 | for i in range(len(listA)): print listA[i], listB[i] |
然而,这是Python的可憎之处。
这里有一种不使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> 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 |
然而,
通常,
我提供了一个使用lambda函数的版本。请注意,如果两个列表的长度不相同,将在相应的位置打印一个
1 2 3 4 5 6 7 8 9 10 | >>> 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 |