本文介绍了在Python 3中获取`OrderedDict`的第一项的最短方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3中获取第一项OrderedDict的最短方法是什么?

What's the shortest way to get first item of OrderedDict in Python 3?

我最好的:

list(ordered_dict.items())[0]

又长又丑.

我可以想到:

next(iter(ordered_dict.items()))       # Fixed, thanks Ashwini

但这不是很自我描述.

But it's not very self-describing.

还有更好的建议吗?

推荐答案

可读性编程实践

通常,如果您觉得代码不是自描述的,通常的解决方案是将其分解为命名函数:

Programming Practices for Readabililty

In general, if you feel like code is not self-describing, the usual solution is to factor it out into a well-named function:

def first(s):
    '''Return the first element from an ordered collection
       or an arbitrary element from an unordered collection.
       Raise StopIteration if the collection is empty.
    '''
    return next(iter(s))

有了该 helper函数,随后的代码将变得非常易读:

With that helper function, the subsequent code becomes very readable:

>>> extension = {'xml', 'html', 'css', 'php', 'xhmtl'}
>>> one_extension = first(extension)

从集合中提取单个值的模式

set dict OrderedDict ,生成器或其他不可索引的集合中获取元素的常用方法是:

Patterns for Extracting a Single Value from Collection

The usual ways to get an element from a set, dict, OrderedDict, generator, or other non-indexable collection are:

for value in some_collection:
    break

和:

value = next(iter(some_collection))

后者很不错,因为 next()函数允许您在collection为空的情况下指定默认值,也可以选择使其引发异常. next()函数也明确要求下一个项目.

The latter is nice because the next() function lets you specify a default value if collection is empty or you can choose to let it raise an exception. The next() function is also explicit that it is asking for the next item.

如果您实际上需要建立索引和切片以及其他序列行为(例如为多个元素建立索引),则可以简单地使用list(some_collection)转换为列表或使用[itertools.islice()][2]:

If you actually need indexing and slicing and other sequence behaviors (such as indexing multiple elements), it is a simple matter to convert to a list with list(some_collection) or to use [itertools.islice()][2]:

s = list(some_collection)
print(s[0], s[1])

s = list(islice(n, some_collection))
print(s)

这篇关于在Python 3中获取`OrderedDict`的第一项的最短方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 04:39