我该如何避免在for循环中声明未使用的变量? [英] How can I get around declaring an unused variable in a for loop?

查看:144
本文介绍了我该如何避免在for循环中声明未使用的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果我有一个列表理解:

If I have a list comprehension (for example) like this:

['' for x in myList]

有效地创建一个新列表,该列表对列表中的每个元素都有一个空字符串,但我从不使用x.有没有一种更简洁的编写方式,所以我不必声明未使用的x变量?

Effectively making a new list that has an empty string for every element in a list, I never use the x. Is there a cleaner way of writing this so I don't have to declare the unused x variable?

推荐答案

_是for循环和元组分配中被忽略成员的标准占位符名称,例如

_ is a standard placeholder name for ignored members in a for-loop and tuple assignment, e.g.

['' for _ in myList]

[a+d for a, _, _, d, _ in fiveTuples]

顺便说一句,您的列表可以在没有列表理解的情况下编写(假设您要创建不可变成员(例如字符串,整数等)的列表.

BTW your list could be written without list comprehension (assuming you want to make a list of immutable members like strings, integers etc.).

[''] * len(myList)

这篇关于我该如何避免在for循环中声明未使用的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆