Python3 | 占位符 _

只循环不使用变量的优美方式

Posted by Haauleon on November 1, 2017

背景

  有时候只想创建一个循环,但是不想去使用变量的值,不使用变量的话又会造成浪费,另外 IDE 也会提示定义的变量没有被用到。



使用技巧

一、for 循环

  for _ in range(n) 语法仅用于创建一个循环。使用 _ 占位符表示不在意变量的值,只用于循环遍历 n 次,无法打印变量值。

实例:

1
2
for _ in range(5):
    print("美滋滋")


运行结果:

1
2
3
4
5
美滋滋
美滋滋
美滋滋
美滋滋
美滋滋



二、列表

  在一个序列中只想取头和尾,也可以使用占位符 _ ,* 表示有 0 或多个。

1
2
3
4
5
6
nums = [1,2,3,4,5]
head, *_, tail = nums
print("head = {}".format(head))
print("tail = {}".foramt(tail))
print("type(_) = {}".foramt(type(_)))
print("_ = {}".format(_))


运行结果:

1
2
3
4
head = 1
tail = 5
type(_) = <class 'list'>
_ = [2, 3, 4]