Python字典到排序元组,这可以做得更好吗?

发布于 2024-11-16 11:27:25 字数 965 浏览 8 评论 0原文

我的输入有一个具有以下特征的字典:

  • 每个值都是整数、字符串或可迭代的(字符串除外)。
  • 如果元素是可迭代的,则该可迭代中的每个元素将只是字符串或整数。

例如:

mydict = {
    'one': 1,
    'two': '23',
    'three': 3,
    'four': [
        7,
        '6',
        5,
        8
    ],
    'nine': 9
}

我需要将输入转换为元组列表,其中每个元组都是一个键/值对。对于可迭代元素,每个元素都有一个键/值对,按值排序。例如,上述输出应该是:

('four', 5)
('four', 7)
('four', 8)
('four', '6')
('nine', 9)
('one', 1)
('three', 3)
('two', '2')

我目前使用以下生成器实现了此功能:

def dict_to_sorted_tuples(unsorted_dict):
    for key in sorted(unsorted_dict):
        if isinstance(unsorted_dict[key], basestring):
            yield key, unsorted_dict[key]
            continue
        try:
            for v in sorted(unsorted_dict[key]):
                yield key, v
        except:
            yield key, unsorted_dict[key]

print list(dict_to_sorted_tuples(mydict))

我觉得这可以以更干净的方式完成,有什么改进建议吗?

I have an dictonary for my input with the following characteristics:

  • Each value will be either an integer, string or iterable (other than a string).
  • If the element is an iterable, each element in that iterable will only be a string or integer.

ex:

mydict = {
    'one': 1,
    'two': '23',
    'three': 3,
    'four': [
        7,
        '6',
        5,
        8
    ],
    'nine': 9
}

I need to convert the input to a list of tuples where each tuple is a key/value pair. For iterable elements, there will be a key/value pair for each of its elements, sorted by value. For example, output for the above should be:

('four', 5)
('four', 7)
('four', 8)
('four', '6')
('nine', 9)
('one', 1)
('three', 3)
('two', '2')

I currently have this implemented using the following generator:

def dict_to_sorted_tuples(unsorted_dict):
    for key in sorted(unsorted_dict):
        if isinstance(unsorted_dict[key], basestring):
            yield key, unsorted_dict[key]
            continue
        try:
            for v in sorted(unsorted_dict[key]):
                yield key, v
        except:
            yield key, unsorted_dict[key]

print list(dict_to_sorted_tuples(mydict))

I feel this can be done in a cleaner fashion, any suggestions for improvements?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

拍不死你 2024-11-23 11:27:25
>>> sorted((i,k) for i,j in mydict.items() for k in ([j] if isinstance(j, str) or isinstance(j, int) else j))
[('four', 5), ('four', 7), ('four', 8), ('four', '6'), ('nine', 9), ('one', 1), ('three', 3), ('two', '2')]

这里的想法是,如果值是 intstr,则将其放入 list 中。现在问题被简化了,因为你有一个可以随时迭代的值

如果你确实确定只需要检查 intstr (不是子类或 unicode),你可以只使用

sorted((i,k) for i,j in mydict.items() for k in ([j] if type(j) in (int, str) else j))

如果值可以是unicode,你应该使用isinstance(j, basestring)而不是isinstance(j, str)

>>> sorted((i,k) for i,j in mydict.items() for k in ([j] if isinstance(j, str) or isinstance(j, int) else j))
[('four', 5), ('four', 7), ('four', 8), ('four', '6'), ('nine', 9), ('one', 1), ('three', 3), ('two', '2')]

The idea here is that if the value is an int or a str, you put it in a list. Now the problem is simplified because you have a value you can always iterate over

If you are really sure you only need to check for int or str (not subclasses or unicode), you could just use

sorted((i,k) for i,j in mydict.items() for k in ([j] if type(j) in (int, str) else j))

If the value can be unicode, you should use isinstance(j, basestring) instead of isinstance(j, str)

彡翼 2024-11-23 11:27:25
for values in sorted(mydict.items()):
    if isinstance(values[1], list):
        for x in sorted(values[1]):
            print (values[0], x,)
    else:
        print values
for values in sorted(mydict.items()):
    if isinstance(values[1], list):
        for x in sorted(values[1]):
            print (values[0], x,)
    else:
        print values
羞稚 2024-11-23 11:27:25
def dict_to_sorted_tuples(unsorted_dict):
    res = []
    for k, v in sorted(unsorted_dict.iteritems()):
        if isinstance(v, (list, tuple)):
            res.extend((k, _v) for _v in sorted(v))
        else:
            res.append((k, v))
    return res
def dict_to_sorted_tuples(unsorted_dict):
    res = []
    for k, v in sorted(unsorted_dict.iteritems()):
        if isinstance(v, (list, tuple)):
            res.extend((k, _v) for _v in sorted(v))
        else:
            res.append((k, v))
    return res
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文