我是 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/