英文:
Returning empty list
问题
Sure, here's the translated code part:
我有一个关于我的程序的问题,我试图检查字母表中哪些字母没有出现在列表中,不幸的是,它返回一个空列表,我不知道为什么。
我尝试了很多方法,但它仍然不起作用...
import string
def get_missing_letters(s):
missing =[]
alphabet = list(string.ascii_lowercase)
s = list(s)
for letter in s:
if letter not in alphabet:
missing.append(letter)
return missing
print(get_missing_letters("abcdefgpqrstuvwxyz"))
英文:
Hi I have problem with my program, I try to check which letters in alphabet doesn't appear in list, unluckily it returns empty list I don't know why
I tried many ways but it still doesn't work...
import string
def get_missing_letters(s):
missing =[]
alphabet = list(string.ascii_lowercase)
s = list(s)
for letter in s:
if letter not in alphabet:
missing.append(letter)
return missing
print(get_missing_letters("abcdefgpqrstuvwxyz"))
答案1
得分: 1
你应该以另一种方式检查它。
for letter in alphabet:
if letter not in s:
missing.append(letter)
并且将你的返回语句移到循环之外。
英文:
You should check it the other way.
for letter in alphabet:
if letter not in s:
missing.append(letter)
and also bring your return statement out of the loop.
答案2
得分: -1
以下是您要的翻译内容:
你有两个问题,return
发生在第一次迭代之后,实际上你是在检查你的字符串中的字母是否存在于 ascii_lowercase
而不是相反的情况。
def get_missing_letters(s):
missing = []
s = list(s)
for letter in list(string.ascii_lowercase):
if letter not in s:
missing.append(letter)
return missing
print(get_missing_letters("abcdefgpqrstuvwxyz"))
# ['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
另一种查找差异的方法是使用 set
:
def get_missing_letters(s):
return set(string.ascii_lowercase).difference(s)
# 或者
return set(string.ascii_lowercase) - set(s)
print(get_missing_letters("abcdefgpqrstuvwxyz"))
# {'j', 'n', 'k', 'l', 'i', 'm', 'o', 'h'}
如果顺序对您很重要,可以对其进行排序:
def get_missing_letters(s):
missing = set(string.ascii_lowercase).difference(s)
return sorted(missing)
print(get_missing_letters("abcdefgpqrstuvwxyz"))
# ['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
英文:
You have two issues, the return
happens after the first iteration and you are actually checking if the letters in your string exists in ascii_lowercase
instead of the opposite
def get_missing_letters(s):
missing = []
s = list(s)
for letter in list(string.ascii_lowercase):
if letter not in s:
missing.append(letter)
return missing
print(get_missing_letters("abcdefgpqrstuvwxyz"))
# ['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
Another way to find the diff is to use set
def get_missing_letters(s):
return set(string.ascii_lowercase).difference(s)
# or
return set(string.ascii_lowercase) - set(s)
print(get_missing_letters("abcdefgpqrstuvwxyz"))
# {'j', 'n', 'k', 'l', 'i', 'm', 'o', 'h'}
You can sort it if the order is important to you
def get_missing_letters(s):
missing = set(string.ascii_lowercase).difference(s)
return sorted(missing)
print(get_missing_letters("abcdefgpqrstuvwxyz"))
# ['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论