【问题标题】:Dictionary of Lists: Sort lists and maintain relative index position列表字典:对列表进行排序并保持相对索引位置
【发布时间】:2014-07-29 21:27:58
【问题描述】:

我有一个 OrderedDict 列表,例如:

data = OrderedDict([('a', [3, 2, 1]]), ('b', [z, y, x])])

我想按数据['a'] 对两个列表进行排序。结果如下:

OrderedDict([('a', [1, 2, 3]]), ('b', [x, y, z])])

元素在所有列表中保持相对索引位置的位置。

我可以通过跟踪索引来做到这一点:

sorted_data = sorted([(t, i) for t, i in zip(data['a'],range(len(data['a'])))])

但这需要另一个循环来整理其他列。这个例子被缩短了——有更多的字典条目。有没有更 Pythonic 的方式来做到这一点,比如 operator.itemgetter?

谢谢。

【问题讨论】:

    标签: list sorting python-3.x dictionary


    【解决方案1】:

    我现在会采取我自己的答案,直到有人提交更精致的东西。这是我的解决方案,但看起来很笨拙:

    sortedData = sorted([(t, i) for t, i in zip(data['a'],range(len(data['a'])))])
    sortedIndex = [i[1] for i in sortedData]
    for key in data.keys():
        data[key] = [ data[key][i] for i in sortedIndex]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多