与字母列表相比,我试图从字符串中获取共享字母。我只返回与 w 共享的 l 的最后一个字母。我想要所有共享的信件。
def f(w,l):
common = []
for i in w:
if in i in l:
return common.append(i)
只要i在l你的代码中return,它就会立即退出你的函数。而是这样做:
def f(w,l):
common = []
for i in w:
if i in l:
common.append(i) # no return needed so it will collect all
return common
确保common在函数末尾返回,以便获得存储在common.
尝试这个:
def f(w,l):
common = []
for i in w:
if i in l:
common.append(i)
return common
问题是.append列表的方法返回None。你第一次从函数返回.append,所以你总是None要从函数返回。
我认为您真正要寻找的是列表理解:
def f(w,l):
return [i for i in w if i in l]
正如其他人指出的那样,您可能希望选择更具描述性的变量名称。