簡體   English   中英

使用python和xlrd,從電子表格中讀取2列的最佳方法是什么

[英]Using python and xlrd, what is the best way to read 2 columns from a spreadsheet

我有一個具有2列的Excel電子表格。 像這樣

| ColA | ColB |
|密鑰| 價值|
| 1 | 測試
| 2 | test2 |
| 3 | test4 |

我想將這兩列讀成字典。 我目前有這項工作,但無法弄清楚如何提取每個鍵值對

  sh = wb.sheet_by_index(0)
  for rownum in range(sh.nrows):
      print sh.row_values(rownum)

你很親密 如果要從僅包含鍵和值的工作表中構建字典,請在前兩列中進行

print dict(sh.row_values(rownum) for rownum in range(sh.nrows))

如John Y所述,如果您需要提取兩個具有索引i(鍵)和j(值)的特定列,則可以改為:

print dict((sh.cell_value(rownum, i), sh.cell_value(rownum, j)) for rownum in range(sh.nrows))

關鍵是dict()可以從(鍵,值)元組的可迭代元組構建字典。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM