python - 有趣的 Python 习语,用于删除单个条目列表中的唯一项

标签 python

今天偶然发现了这个,认为它可能值得讨论。

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 )

总的来说,我对这个想法感到困惑。他对自由断言和增加的可读性(它应该成为一种模式)提出了一个令人信服的论点。另一方面,直到/如果它变得流行,它会有点难以阅读。

社区怎么看?

最佳答案

博客发布者希望单个语句用作 (1) 从列表中提取项目,(2) 断言,以及 (3) 作为注释告诉用户该列表只有一个项目。

我非常喜欢尽量减少代码行数,但我更喜欢以下内容:

assert len(stuff) == 1, "stuff should have length 1 but has length %d" % len(stuff)
thing = stuff[0]

显式优于隐式。

关于python - 有趣的 Python 习语,用于删除单个条目列表中的唯一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3812858/

相关文章:

python - Pyparsing 找到文件中的第一次出现

python - 替换 pyspark 数据框中列名中的字符

python - 为什么 open(True, 'w' ) 会像 sys.stdout.write 一样打印文本?

python - 在 Python Pandas 中创建新的 QuarterEnd 列

python - 集合中的命名约定 : why are some lowercase and others CapWords?

python - 使用python仅对时间序列中的非NaN数据求和

python - 使用 Open CV 屏蔽水平线和垂直线

python - 如何找到两个目录之间的相对路径?

python - Django 开发版本与稳定版本

python - 如何在 gunicorn 访问日志中添加响应时间