gpt4 book ai didi

python - 将字符串中的真值转换为 Int

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:14 24 4
gpt4 key购买 nike

list = ['JACOBIS','LIMANIS','FOXTROT']
word = input('enter a word in the list')
generatedword = (random.choice(list))

程序运行时的可能场景,如果用户输入 FOXTROT 但单词是 JACOBIS:

print("Your word contains 1/7 correct characters")

可能的解决方案:

if word == generatedword:
print ("your word contains 7/7 correct characters")

in 操作是否适合这种情况?例如:

print ("your word contains", len(str(generatedword)), "/7")

print ("your word contains", len(str(word)) in generatedword, "/7")

最佳答案

首先,in 不是函数,它是成员检查操作的运算符。

其次你不能使用 in 因为你可能有一个像 hello 和另一个像 he 这样的词,而这是 while hehello但是字符长度不一样。

相反,您可以使用 set.intersection() 来查找常见字符:

>>> a = "FOXTROT"
>>> b = "JACOBIS"

>>> len(set(a).intersection(b))
1

但请注意,您需要将其除以 set(b) 的长度,以处理具有重复字符的单词。

由于这种方法将根据唯一字符给出计数,如果你想为以下示例的交集获取 2,你可以使用 str.count()sum() 函数如下:

>>> a = 'FOXTROT'
>>>
>>> b = 'JACOBIS'

>>> sum(a.count(i) for i in set(b))
2

这将为您提供第一个字符串中所有字符在第二个字符串中的总和。

关于python - 将字符串中的真值转换为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37259336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com