gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:53 24 4
gpt4 key购买 nike

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

关于python - 如何从 python 字典列表中创建范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32918894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com