[英]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.