2017-12-27 564 views
2

我有一些代碼在一個python腳本,看起來像創建從OpenPyXL元組:獲得手機數據環行

for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50) 
    print(row) 

它返回

(<Cell 'States'.A2>, <Cell 'States'.B2>) 
(<Cell 'States'.A3>, <Cell 'States'.B3>) 
... 
(<Cell 'States'.A50>, <Cell 'States'.B50>) 

我想拉值從'A-column'和'B-column'使用cell.value進一步分割'B-column'(用逗號分隔的值)(例如7,100或100,7),然後將這些值添加到字典中看起來像:

StatesPriority = { 
    A2 : (B2.ValueBeforeComma, B2.ValueAfterComma) 
    A3 : (B3.ValueBeforeComma, B3.ValueAfterComma) 
    ... 
    A50 : (B50.ValueBeforeComma, B50.ValueAfterComma) 
} 

但是,我更關心OpenPyXL函數從返回的元組中獲取值。我想我可以用一點點時間用我自己的逗號分解值。

Python版本:3.6.3 OpenPyXL版本:2.4.9

所有幫助表示讚賞!

回答

1

row是有兩個元素的元組,因此,您可以分配期間解壓:

StatesPriority = {} 
for row in sheet.iter_rows(min_row=2, max_col=2, max_row=50) 
    cell_a, cell_b = row 
    StatesPriority[cell_a.value] = (tuple(cell_b.value.split(',')) 
+0

,完美的工作!我不知道內置的.split。非常感謝! :) – Bill