【问题标题】:Having trouble iterating through a two dimensional array in python and adding items to a dictionary [duplicate]在python中遍历二维数组并将项目添加到字典时遇到问题[重复]
【发布时间】:2015-11-29 20:56:10
【问题描述】:

这个程序应该做的是使用两个循环遍历数组,并将第一个集合中不是数字的所有内容变成一个键。键没有按我期望的顺序添加到字典中。这门课还有更多内容,但这是给我带来麻烦的部分。

class Sorter(): 
def __init__(self, vals): 
    self.vals = vals

def borda(self): 
    bordaContainer = { }
    arrayLength = len(self.vals) 
    for outsides in range(arrayLength):
        for insides in range(len(self.vals[outsides])):
            currentChoice = self.vals[outsides][insides]
            if outsides ==0 and insides != len(self.vals[outsides])-1:
                bordaContainer[currentChoice] = ''
    return bordaContainer

inputArray = [['A','B','C','D',10],['C','D','B','A',4],['D','A','B','C',7]]
first = Sorter(inputArray)
print first.borda()

结果:

{'A': '', 'C': '', 'B': '', 'D': ''} 

我应该得到 {'A': '', 'B': '', 'C': '', 'D': ''}。任何对正在发生的事情的解释都会很棒,谢谢!

【问题讨论】:

  • python 中的字典没有排序。如果需要,请使用 collections 模块中的 OrderedDict
  • python 中的字典不保留插入键的顺序。如果您确实想维持订单,请尝试使用OrderedDictdocs.python.org/2/library/…
  • 这个问题的本质已经在 Stack Overflow 上被问过无数次了。如果您想了解为什么 Python 字典是无序的,this 有一些很好的答案。

标签: python arrays dictionary


【解决方案1】:

字典没有排序。您可能想使用 OrderedDict:https://pymotw.com/2/collections/ordereddict.html

【讨论】:

    【解决方案2】:

    Python 字典中包含hashable 对象作为键,您不能排除它的顺序。如果你尝试下面的代码,你可以看到。

    >>> d = {'a': 1, 'b': 2, 'c':3}
    >>> d
    {'a': 1, 'c': 3, 'b': 2}
    

    您可以在集合中使用OrderedDict,如下所示..

    >>> from collections import OrderedDict
    >>> d1 = OrderedDict([('a', 1), ('c', 3), ('b', 2)])
    >>> d1
    OrderedDict([('a', 1), ('c', 3), ('b', 2)])
    >>> for i in d1:
    ...     print i, d1[i]
    ... 
    a 1
    c 3
    b 2
    

    【讨论】:

    • 对不起,我对字典有点陌生,并认为我有一个逻辑错误。感谢大家的回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多