为什么我只从列表中获取一个项目

时间:2013-11-13 00:41:06

标签: python string list

我试图从字符串中获取共享字母与字母列表相比较。我只返回与w共享的l的最后一个字母。我想要所有的共享信件。

def f(w,l):
    common = []
    for i in w:
        if in i in l:
            return common.append(i)

3 个答案:

答案 0 :(得分:6)

只要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,以便获得{{1}}中存储的所有值。

答案 1 :(得分:0)

试试这个:

def f(w,l):
    common = []
    for i in w:
        if i in l:
            common.append(i)

    return common

答案 2 :(得分:0)

问题是列表的.append方法返回None。你第一次.append时从函数返回,所以你总是从函数返回None

我认为你真正想要的是列表理解:

def f(w,l):
    return [i for i in w if i in l]

正如其他人所指出的那样,您可能希望选择更多描述性变量名称。

相关问题