gpt4 book ai didi

python - python中的列表切片问题

转载 作者:行者123 更新时间:2023-12-01 05:04:35 24 4
gpt4 key购买 nike

这段代码看起来应该可以工作。它对“条纹”(字母-辅音-字母等)的单词数进行求和,然后返回总和。但是,当我用 print (striped("My name is ...") ) 测试它时,它只计算 myis 并给我总和是 2 而不是 3...为什么缺少 name

VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"


def striped(text):

my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = VOWELS.lower()
consonants = CONSONANTS.lower()

for word in text:
word = word.lower()
if ((word[::2] in vowels and word[1::2] in consonants)\
or (word[::2] in consonants and word[1::2] in vowels))\
and len(word) > 1:
print (word)
my_sum += 1

return my_sum

最佳答案

这是一个带有列表的解决方案。您的代码的问题在于,当您使用 [::2] 时,长度超过两个字符的单词会返回子字符串,而不是测试它们是否包含在 元音 中的单个字符/常量。通过先将其转换为列表,您可以检查列表中的每个项目是否包含在相应的字符集中。

VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"


def striped(text):

my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = VOWELS.lower()
consonants = CONSONANTS.lower()

for word in text:
word = word.lower()

if ((all(c in vowels for c in list(word[::2]))\
and all(c in consonants for c in list(word[1::2])))\
or (all(c in consonants for c in list(word[::2]))\
and all(c in vowels for c in list(word[1::2]))))\
and len(word) > 1:
print (word)
my_sum += 1

return my_sum

print striped("My name is")

关于python - python中的列表切片问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25315451/

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