Python for 循环控制变量在声明前访问

标签 python for-loop

我是 python 新手,我试图理解以下行:

    "".join(char for char in input if not unicodedata.category(char).startswith('P'))

来源:https://stackoverflow.com/a/11066443/3818487

此代码从输入中删除所有 unicode 标点符号。我不明白为什么它有效。据我所知,它只是迭代输入中的所有字符,忽略标点符号。在 for 循环中声明之前如何访问 char?我有java背景,所以这对我来说很困惑。

最佳答案

这种理解在常规代码中看起来更像下面这样(使用列表来存储非标点符号字符)。

#input is defined somewhere prior to the loop
output = []
for char in input:
    if not unicodedata.category(char).startswith('P'):
        output.append(char)
''.join(output)

推导式首先迭代循环部分,并在左侧迭代值。

关于Python for 循环控制变量在声明前访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37757308/

相关文章:

java - 使用 "for-loops"

java - 在 FOR 循环之前调用时未调用 Settext

python - 如何使用日期和数据列在 python 中访问、调用或提取单变量时间序列数据的元素

python - 合并两个 Google App Engine 数据存储结果?

python - Robot Framework f中的文件上传

python - 如何发送模板中的一组对象?

python/django for循环和列表属性

Windows 命令行 : Display fully qualified paths of and count files in a directory and its subdirectories that have a user-defined extension

java - 从比赛中打印高于平均时间

python - 使用方括号对 Pytorch 张量进行子集化