【问题标题】:For loop in a function - not iterating through string函数中的 For 循环 - 不遍历字符串
【发布时间】:2021-09-01 06:12:03
【问题描述】:

我希望通过用户输入接收两个字符串,并调用一个函数将第一个字符串中的每个字符与第二个字符串中的每个字符进行匹配,并对它们进行计数。所以 String 1 = bad 和 String 2 = bed 将返回匹配的 2 个字符的计数

def occurrences(text1, text2):

    count = 0

    for c in firstword :
        if c == secondword :
            count += 1
            return True
    return False


firstword = input("Enter first word")

secondword = input("Enter second word")

occurrences(firstword, secondword) 

将两个字符串传递给函数会返回 false,即使它们是完全相同的单词。只是想知道我在这里的 for 循环哪里出错了,为什么 if 语句不匹配字符串和计数。 谢谢

【问题讨论】:

  • return sum(1 for i in text1 if i in text2)?
  • 只需将 == 更改为 if a in b 而不是 if a == b 即可

标签: python function for-loop


【解决方案1】:
for c in firstword :
    if c == secondword :

您正在逐个字符地迭代第一个字符串 (for c in firstword),并将该字符与 整个 第二个字符串 secondword 匹配。更不用说:

  • 您正在使用外部变量firstwordsecondword 而不是函数参数text1text2
  • 您的函数仅返回 TrueFalse,它甚至不会尝试返回计数
  • return True就在第一场比赛,如果有的话,所以它永远不会超过1

要逐个字符比较两个字符串,您需要并行迭代两个字符串。最好的方法是zip:

count = 0
for c1, c2 in zip(text1, text2):
    if c1 == c2:
        count += 1

可以用sum做成单行:

def occurrences(text1, text2):
    return sum(c1 == c2 for c1, c2 in zip(text1, text2))

愚蠢的奖金回合,如果您想真正花哨并实用

from operator import eq
from itertools import starmap

def occurrences(text1, text2):
    return sum(starmap(eq, zip(text1, text2)))

【讨论】:

  • 呃,这完全解释了它,我以为我完全错误地接近它。谢谢你的解释!
  • 哇!我以为是反过来的。现在我明白了。谢谢
  • “花哨”的方式在我看来确实很愚蠢。压缩它们只是为了你需要星图来解压它们?我只会做sum(map(eq, text1, text2))
  • @don't 呃,确实,这有点过于复杂了,不是吗?
【解决方案2】:

function 中,当您到达return 时,该功能正在结束,因此当您想要计数并结束for-loop 返回您的计数器时,不要在for-loop 中设置return。 试试这个:

def occurrences(text1, text2):
    count = 0
    for c in firstword :
        if c in secondword :
            count += 1
    return count

firstword = input("Enter first word : ")
secondword = input("Enter second word : ")
occurrences(firstword, secondword)

输出:

Enter first word : bad
Enter second word : bed
2

【讨论】:

  • 谢谢!我知道我在做一些愚蠢的事情,但不知道我哪里错了。另一个愚蠢的问题,我看到你将我的 if c == secondword 更改为 if c in secondword 当我这样做时 == 这是否意味着它试图将 c 的单个字符与整个 secondword 匹配为字符串?
  • @RenaissanceMan,在您的代码中,您检查 char == string 这是错误的,因为使用 in 检查字符串是否具有字符,如下所示:char in string跨度>
猜你喜欢
  • 1970-01-01
  • 2023-01-24
  • 1970-01-01
  • 1970-01-01
  • 2014-01-29
  • 2021-04-02
  • 2023-03-23
  • 2016-01-24
  • 2015-01-17
相关资源
最近更新 更多