这个for循环和“new=''”如何工作?

2024-10-02 00:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

def shortenPlus(s):
    # Yer Code 'Ere Mate!
    # Aye Aye cap'
    new = ''
    prior = ''
    for x in s:
        if not (x in 'aeiou' and prior.isalpha()):
            new += x
        prior = x
    return new

print(shortenPlus("I've information vegetable, animal and mineral"))

这是我从this线程中找到的代码。我很难理解for循环的“if not”部分是如何工作的,以及为什么我们有新的和先前的语句

我知道我们从字符串中获取一个变量,如果这个变量不在“aeiou”中,并且之前的容器没有字母表中的任何内容,那么您可以将这个变量添加到新的。但是如果previor是I,x是v,它不满足previor的标准,但是它仍然将它添加到new中

到目前为止,我就是这样理解的。请让我知道我的误解


Tags: andinnewforifdefnotcode
3条回答

让我们扩展一下

if not(x in 'aeiou' and prior.isalpha()): ...

inner = x in 'aeiou' and prior.isalpha()
if not inner:
    ...

为了清楚起见。现在,inner将为真当且仅当两个条件都为真时:

  • x是元音
  • 前一个字符是一个字母

如果这些中的不是真的,那么inner将是假的。因此,最初的测试:

not(x in 'aeiou' and prior.isalpha())

否定这一点,如果这两个条件都满足,则将为False。如果其中一个(或两个!)未满足,则它将为True,并且将计算If语句。因此,如果满足以下条件,将对if语句进行评估:

  • x不是的值
  • 和/或前一个字符不是字母

你有点逻辑上的误解。代码指定NOT (A AND B);这相当于NOT A OR NOT B。换言之:

if this variable is NOT in 'aeiou', OR the prior container does NOT have anything from the alphabet, then you add this variable to new

那么,继续假设,如果priorI,而xv,那么:

  • x in 'aeiou'为假
  • prior.isalpha()是真的

因此:

  • x in 'aeiou' and prior.isalpha()为假

因此:

  • not(x in 'aeiou' and prior.isalpha())是真的

I am having trouble understanding [...] why we have new and prior statements.

newprior是变量,而不是语句。代码使用new构建一个新字符串,使用prior存储for循环上一次迭代中的字符

if this variable is NOT in 'aeiou', and the prior container does NOT have anything from the alphabet

你对逻辑的理解不太正确。如果两个{}和{}的计算结果都为false,则执行{}行,这(perDe Morgan's theorem)相当于说,如果或者{}或者{}(或者两者兼而有之),则执行{}行

因此,代码将向字符串添加一个字符,只要它不是元音,前一个字符不是字母,或两者都不是

相关问题 更多 >

    热门问题