【问题标题】:Sort the values of lists corresponding to a row of excel numbers in a dictionary in descending order using openpyxl使用openpyxl对字典中一行excel数字对应的列表值进行降序排序
【发布时间】:2022-01-06 15:50:26
【问题描述】:

我目前的任务是按降序对与一行 excel 数字对应的列表的值进行排序,并将它们存储在字典中。

例如,我有一个这样的 excel 文件:

0.296178 0.434362 0.033033 0.758968

0.559323 0.455792 0.770423 0.770423

我使用下面的代码创建了一个字典,将每个单元格的值存储为一个列表,每行的键是行号。

from openpyxl import load_workbook
import operator

vWB = load_workbook(filename="voting.xlsx")
vSheet = vWB.active

# Creating the Dictionary of agents and their alternative values
dictionary = {
    i + 1: [cell.value for cell in row[0:]]
    for i, row in enumerate(vSheet.rows)
}

输出:

{1: [0.296177589742431, 0.434362232763003, 0.0330331941352554, 0.758968208500514], 2: [0.559322784244604, 0.455791535747786, 0.770423104229537, 0.770423104229537]....etc }

但是,我不确定如何在不更改键顺序的情况下按降序排列每个列表的值。

我想要什么:

{1: [0.758968208500514, 0.434362232763003, 0.296177589742431, 0.0330331941352554, 0.758968208500514], 2: [0.770423104229537, 0.770423104229537, 0.559322784244604, 0.455791535747786]....etc }

如何按降序对每个键的值列表进行排序?

【问题讨论】:

  • 您确实应该更新您的原始问题,并在添加时简单地对每一行进行排序。
  • 对不起,我如何更新原始问题这是我第一次使用这个网站。
  • 使用编辑功能即可。

标签: python dictionary collections openpyxl


【解决方案1】:

你可以这样试试

d = {1: [0.758968208500514, 0.434362232763003, 0.296177589742431, 0.0330331941352554, 0.758968208500514],
 2: [0.770423104229537, 0.770423104229537, 0.559322784244604, 0.455791535747786]}

for key, value in d.items():
    print(sorted(value,reverse=True))

输出 [0.758968208500514, 0.758968208500514, 0.434362232763003, 0.296177589742431, 0.0330331941352554] [0.770423104229537, 0.770423104229537, 0.559322784244604, 0.455791535747786]

【讨论】:

  • 有没有办法用这个来更新字典顺序。非常感谢您的帮助。
  • 字典顺序是什么意思?什么用第二个替换第一个键值?
猜你喜欢
  • 2011-02-22
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
  • 2014-02-14
相关资源
最近更新 更多