Python中的”_”

In Python, you can use the _ field to grab the last computed value.
最近两天在不同的程序里面看到了,这玩意太cool了!

在Gensim里面再次看到了‘_’这个东西,发现根本不是上面所说的功能。在Google Group问了之后,发现豁然开朗了。

原来‘_’在Python中有两个功能

  1. grab the last computed value
  2. tell the reader the value is not used, as a way to increase readiability

关于第二点,具体的例子是:

  ids = [id for id, _ in doc] 

means that from each “doc” you get two
things: id, and something else BUT this something is being ignored for now
(presumably because it is not needed )

So, if

 a=[(1,2),(3,4)]

then

 >>> [i for i,_ in a]
 [1, 3]
Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s