从单个条目列表中删除唯一项的有趣Python惯用语

3

今天偶然发现了这个,觉得值得讨论。

Python idiom for taking the single item from a list

It sometimes happens in code that I have a list, let’s call it stuff, and I know for certain that this list contains exactly one item. And I want to get this item and put it in a variable, call it thing. What’s the best way to do this? In the past I used to do this:

thing = stuff[0]

But I think that’s not the best idiom. I came up with a better one:

(thing,) = stuff

Why is this one better?

Readability: It lets the reader know that stuff has exactly one element.

Free assert: It makes Python assert that stuff has exactly one element, so if I was wrong in my original assumption that stuff has exactly one element, Python will shout at me before this manifests itself as a hard-to-find bug someplace else in the program.

Hard to miss: The previous method had a [0] at the end. Now, that’s easy to notice in a line as short as thing = stuff[0]. But what if the line were something messy like this:

thing = some_dict[my_object.get_foobar_handler()][0]

In this case, the [0] at the end is easy to miss, because when casually glancing the code, it might seem connected to that function call or dict lookup. So the reader might miss the fact that we’re taking an item out of a list here. This would be better in this case:

(thing,) = some_dict[my_object.get_foobar_handler()]

General for any “collection” (props to Ulrik for noting this): This method works even when stuff is a set or any other kind of collection. stuff[0] wouldn’t work on a set because set doesn’t support access by index number. Have fun programming!

(http://blog.garlicsim.org/post/1198230058/python-idiom-for-taking-the-single-item-from-a-list)

总的来说,我对这个想法感到矛盾。他提出了一个有力的论点,即使用free assert可以增加可读性(如果成为一种模式)。另一方面,在它变得流行之前/之后,它有点难以阅读。

社区怎么看?


不做任何评价,只是想提一下,这也可以在没有大括号的情况下实现:thing, = stuff - MattH
1
@Matth:但是没有括号的尾随逗号也很容易被忽视。 - user395760
3个回答

7
博客作者希望有一个单一语句可以实现以下三个功能:(1)从列表中提取一个项目,(2)进行断言,(3)告诉用户该列表只有一个项目。我非常喜欢尽量减少代码行数,但我更喜欢以下写法:
assert len(stuff) == 1, "stuff should have length 1 but has length %d" % len(stuff)
thing = stuff[0]

显式优于隐式。


+1:assert(断言)经常是必要的。非常频繁。你可能认为它只有一个元素。但是你在其他地方可能会遇到问题。 - S.Lott

2

I prefer:

[thing] = stuff

仅仅因为我认为(thing,)很丑,所以我希望更改它。但是总的来说,我喜欢这个概念。


0

一个人很可能会漏掉逗号,我宁愿索引东西而不是把括号(和逗号)放在周围。

我想我现在的写法是 thing = stuff[0]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接