Skip to main content
 首页 » 编程设计

python之如何从 python 字典列表中创建范围

2025年05月04日21hnrainll

我正在使用 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)