2014-09-25 42 views
0

假設我有一個函數get_call_value(row, column),它返回電子表格單元格的值。我有一組與列對應的標籤。我想建立一個字典列表,其中的關鍵字是列標籤。這是我到目前爲止有:在沿線的錯誤使用生成器創建包含一組標籤的字典列表

def _get_rows(self, start_key=1): 
    # List holding lists representing rows 
    out_data = [] 

    # Get row count 
    row_count = num_rows() 
    column_count = num_columns() 

    def get_label_value(row, column): 
     """Generator for getting the cell value at row, column of an Excel sheet 
     """ 
     labels = { 
     0: 'label_1', 
     1: 'label_2', 
     2: 'label_3', 
     } 
     yield (labels[column], get_cell_value(row, column)) 

    return {key: value for (key, value) in get_label_value(xrange(start_key, row_count), xrange(column_count))} 

我的堆棧跟蹤結束:

get_label_value 
    yield (labels[column], get_cell_value(row, column)) 
KeyError: xrange(31) 

我顯然不理解發電機如何工作。有人能告訴我我做錯了什麼嗎?謝謝!

編輯: 我認爲需要進一步澄清,並在我的邏輯中看到我想要做的錯誤。我的預期結果是一個詞典列表。在詞典中的鍵是列標籤和值單元格的值在(行,列),像這樣:

[ 
    {'label_1': value_1, 
    'label_2': value_2, 
    'label_3': value_3, 
    }, 
    { 
    'label_1': another_value_1, 
... 
    } 
] 

考慮到這一點,在return語句我應該是這樣的呢?

回報:

+0

什麼是預期的結果?期望xrange做什麼? – 2014-09-25 02:12:18

回答

1

你試圖將整個xrange對象傳遞給labels [{鍵(鍵,值)get_label_value(x範圍(start_key,ROW_COUNT)的xrange(COLUMN_COUNT))值}]字典,這就是爲什麼你看到這個例外。你真正想要做的是疊代你傳遞給get_label_value兩個xrange對象,這樣就可以建立你想要的類型的字典列表:

def _get_rows(self, start_key=1): 
    # List holding lists representing rows 
    out_data = [] 

    # Get row count 
    row_count = num_rows() 
    column_count = num_columns() 

    def get_label_value(rows, columns): 
     """Generator for getting the cell value at row, column of an Excel sheet 
     """ 
     labels = { 
     0: 'label_1', 
     1: 'label_2', 
     2: 'label_3', 
     } 
     # Yield a dict for each row in the table. The dict contains all the 
     # cells for a given row in the table, where the keys are column labels, 
     # each mapped to a given cell in the row. 
     for row in rows: 
      yield {labels[column] : get_cell_value(row, column) for column in columns} 

    return [cell_dict for cell_dict in get_label_value(xrange(start_key, row_count), xrange(column_count))] 
+0

dano,我編輯了我的問題;我不認爲我的結果很清楚。 – ericso 2014-09-25 03:50:32

+0

除了收益線中的逗號之外,這個工作應該是冒號。如果出於某種原因不超過六個字符,SO不會讓我編輯它。 – ericso 2014-09-25 16:21:05

+0

@ericso謝謝,我修正了這個問題。很高興它對你有效。 – dano 2014-09-25 16:28:00

相關問題