简体   繁体   English

如何从python dicts列表创建范围?

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

I'm using openpyxl to evaluate a worksheet.我正在使用 openpyxl 来评估工作表。 There is one row on this worksheet contains column_group names in merged cells.此工作表上有一行包含合并单元格中的 column_group 名称。 i created a list of dicts where column_group is key and column number is value我创建了一个字典列表,其中 column_group 是键,列号是值

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

now I want to create a group_name:(start_column:end_column) dictionary using col_groups现在我想使用 col_groups 创建一个 group_name:(start_column:end_column) 字典

This is the closest I've been able to get.这是我能得到的最接近的。

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)})

typing group_cols at the python shell prompt gives:在 python shell 提示符下键入 group_cols 给出:

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

The output looks ok but my method feels a bit hackish- any suggestions to be more pythonic will be appreciated输出看起来不错,但我的方法感觉有点hackish - 任何关于更pythonic的建议将不胜感激

A dictionary is the wrong structure, a tuple (name, idx) would be better, for this but you can work with it.字典是错误的结构,元组 (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)

The only time your try statement fails, is when you are at the end of the list, and are trying to access the element after the last element.你的 try 语句唯一失败的时候,是当你在列表的末尾,并试图访问最后一个元素之后的元素时。 In such cases using an if statement is probably better.在这种情况下,使用 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