繁体   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