繁体   English   中英

如何使用 zip function 使用 openpyxl 将列号与 excel 单元格的值相关联

[英]How to use zip function to associate column number with value of excel cell using openpyxl

我正在创建一个字典,其中键应该是行号,字典的值应该是列号列表,其顺序由该行的值确定,按降序排序。

我的代码如下:

from openpyxl import load_workbook

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

d = {}
for idx, row in enumerate(vSheet.values, start=1):
    row = sorted(row, reverse=True)
    d[idx] = row

output:

{1:[0.758968208500514,0.4343622232763003,0.296177758974242431,0.033333194135554]

我想要的是:

{1:[4,2,1,3],2:[3,4,1,2] 等..}

我一直在尝试创建一个数字来表示每个值的列号

genKey = [i for i in range(values.max_column)

然后使用 zip function 将列号与每个值相关联

dict(zip(column key list, values list)

所以我有一个字典,其中列作为键 1,2,n 和值作为值,然后我可以按降序对键进行排序,我可以再次遍历行和 zip,键是行号。

我不确定如何使用这个 zip function 并到达我想要的端点。 欢迎任何帮助。

只需使用enumerate

dictionary = {
    row_id: [cell.value for cell in row]
    for row_id, row in enumerate(vSheet.rows)
}

enumerate可以应用于可迭代对象并返回索引和值元组上的迭代器。 例如:

x = ['a', 'b', 'c']
print(list(enumerate(x)))

产生[("a", 0), ("b", 1), ("c", 2)]

如果要从 1 开始,请使用enumerate(x, 1)

您可以使用枚举

dictionary = {
    i: [cell.value for cell in row[0:]]
    for i, row in enumerate(vSheet.rows)
}

如果您只想要单元格值,这很容易:

d = {}
for idx, row in enumerate(ws.values, start=1):
   row = sorted(row)
   d[idx] = row

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM