关于python:为什么使用下划线(’_’)作为变量名?

Why use underscore ( '_') as a variable name?

本问题已经有最佳答案,请猛点这里访问。

我试图从一些TensorFlow代码中理解这一行代码

1
 _, l = session.run([optimizer, loss], feed_dict=feed_dict)

此行的上下文来自

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
with tf.Session(graph=graph) as session:
  tf.global_variables_initializer().run()
  print('Initialized')
  average_loss = 0
  for step in range(num_steps):
    batch_data, batch_labels = generate_batch(
      batch_size, num_skips, skip_window)
    feed_dict = {train_dataset : batch_data, train_labels : batch_labels}
    _, l = session.run([optimizer, loss], feed_dict=feed_dict)
    average_loss += l
    if step % 2000 == 0:
      if step > 0:
        average_loss = average_loss / 2000
      # The average loss is an estimate of the loss over the last 2000 batches.
      print('Average loss at step %d: %f' % (step, average_loss))
      average_loss = 0
    # note that this is expensive (~20% slowdown if computed every 500 steps)
    if step % 10000 == 0:
      sim = similarity.eval()
      for i in range(valid_size):
        valid_word = reverse_dictionary[valid_examples[i]]
        top_k = 8 # number of nearest neighbors
        nearest = (-sim[i, :]).argsort()[1:top_k+1]
        log = 'Nearest to %s:' % valid_word
        for k in range(top_k):
          close_word = reverse_dictionary[nearest[k]]
          log = '%s %s,' % (log, close_word)
        print(log)
  final_embeddings = normalized_embeddings.eval()

完整代码在这里

https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/5_word2vec.ipynb

为什么下划线用作变量?似乎是这样一个奇怪的选择,但这是来自官方的TensorFlowGithub,所以一定有原因。


当unpacking列表/ _是typically元组,用于以后的你会不会需要的值。如果你仔细看,在这_可变码,是不是真的任何地方使用。

请注意,在Python _到REPL,指的是最新的结果。

1
2
3
4
>>> 2+2
4
>>> _
4