2017-10-18 38 views
0

我一直在试图创建一个程序来验证一个列表中的字符串或该列表中的元素是否包含2个或更多'a',以防万一它不应该将元素保存在新列表中。这是到目前为止我的代码:用双'a'消除列表中的字符串元素

ent = input("Ingresa un listado de palabras separados por coma: ") 
lst_1 = ent.split(",") 
lst_2 = [] 

def cuenta(lst_M): 
    tmp = 0 
    for i in range (0,len(element)): 
     print(lst_M[i]) 
     if lst_M[i] == 'a': 
      tmp += 1 
      print(tmp) 
    return tmp  


for element in lst_1: 
    lst_rev = [i for i in element] 
    cuenta(lst_rev) 
    print("Este es el valor de tmp:",tmp) 
    if tmp <= 2: 
     lst_2.append(element) 
    print(lst_2) 

print(lst_2) 

输出看起来是这样的:

Ingresa un listado de palabras separados por coma: ana,another,person,ana 
a 
1 
n 
a 
2 
Este es el valor de tmp: 0 
['ana'] 
a 
1 
n 
o 
t 
h 
e 
r 
Este es el valor de tmp: 0 
['ana', 'another'] 
p 
e 
r 
s 
o 
n 
Este es el valor de tmp: 0 
['ana', 'another', 'person'] 
a 
1 
n 
a 
2 
Este es el valor de tmp: 0 
['ana', 'another', 'person', 'ana'] 
['ana', 'another', 'person', 'ana'] 

正如你可以看到我用一个函数来计算的“A”的元素中,但数某些原因,函数外部的变量tmp始终为0. 我在做什么错?

+1

您需要在'for'循环中存储'cuenta'方法的返回值:'tmp = cuenta(lst_rev)'。然后检查返回值。 –

+0

它完全工作,你可以把它作为一个aswer,所以我可以接受你的答案! – Zombraz

回答

1

尝试将函数调用的结果分配给一个变量。目前,您正在调用正在返回值的函数,但您并未“捕获”函数调用范围之外的返回值。

tmp = cuenta(lst_rev) 
print("Este es el valor de tmp:",tmp) 
相关问题