Python “x for x in”语法是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47464211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does the "x for x in" syntax mean?
提问by Martin Melichar
What actually happens when this code is executed:
执行此代码时实际发生的情况:
text = "word1anotherword23nextone456lastone333"
numbers = [x for x in text if x.isdigit()]
print(numbers)
I understand, that []
makes a list, .isdigit()
checks for True or False if an element of string (text) is a number. However I am unsure about other steps, especially: what does that "x" do in front of for loop?
我知道,如果字符串(文本)的元素是数字,[]
则生成一个列表,.isdigit()
检查 True 或 False。但是我不确定其他步骤,尤其是:“x”在 for 循环前做了什么?
I know what the output is (below), but how is it done?
我知道输出是什么(如下),但它是如何完成的?
Output: ['1', '2', '3', '4', '5', '6', '3', '3', '3']
采纳答案by ninesalt
This is just standard Python list comprehension. It's a different way of writing a longer for loop. You're looping over all the characters in your string and putting them in the list if the character is a digit.
这只是标准的 Python 列表理解。这是编写更长的 for 循环的另一种方式。如果字符是数字,您将遍历字符串中的所有字符并将它们放入列表中。
See thisfor more info on list comprehension.
有关列表理解的更多信息,请参阅此内容。