簡體   English   中英

如何從python dicts列表創建范圍?

[英]how to create range from a list of python dicts?

我正在使用 openpyxl 來評估工作表。 此工作表上有一行包含合並單元格中的 column_group 名稱。 我創建了一個字典列表,其中 column_group 是鍵,列號是值

col_groups= [{u'Layer': 1}, {u'Single Ended': 17},\
             {u'Single Ended': 22}, {u'Edge Coupled': 27}]

現在我想使用 col_groups 創建一個 group_name:(start_column:end_column) 字典

這是我能得到的最接近的。

group_cols = []
for x, d in enumerate(col_groups):
    try:
        group_cols.append({col_groups[x].keys()[0]:(col_groups[x].values()[0],(col_groups[(x+1)].values()[0] - 1))})
    except:
        group_cols.append({col_groups[x].keys()[0]:(col_groups[x].values()[0],tap_sh.max_column)})

在 python shell 提示符下鍵入 group_cols 給出:

[{u'Layer': (1, 16)}, {u'Single Ended': (17, 21)}, {u'Single Ended': (22, 26)}, {u'Edge Coupled': ( 27, 33)}]

輸出看起來不錯,但我的方法感覺有點hackish - 任何關於更pythonic的建議將不勝感激

字典是錯誤的結構,元組 (name, idx) 會更好,為此,您可以使用它。

# define a sort key (Python 3 compatible)
def sort_key(value):
    "Sort by the value"
    return list(value.values())[-1]

ordered_groups = []
max_column = 34
for group in sorted(col_groups, key=sort_key, reverse=True):
    key, begin = list(group.items())[0]
    end = max_column - 1
    max_column = begin
    ordered_groups.append((key, (begin, end)))
dict(ordered_groups)

你的 try 語句唯一失敗的時候,是當你在列表的末尾,並試圖訪問最后一個元素之后的元素時。 在這種情況下,使用 if 語句可能更好。

col_groups = [{u'Layer': 1}, {u'Single Ended': 17},
              {u'Single Ended': 22}, {u'Edge Coupled': 27}]

group_cols = []
for i in range(col_groups):
    key = col_groups[i].keys()[0]
    first_val = col_groups[i].values()[0]
    if i != len(col_groups) - 1:
        second_val = col_groups[i + 1].values()[0] - 1
    else:
        second_val = tap_sh.max_column
    values = (first_val, second_val)
    group_cols.append({key: values})

暫無
暫無

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

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