Reputation: 15
I may have a noob question, but here it goes. I need to parse through a list and I need the return to be specific. Here is the code:
a = 11
bla = [1,2,3,4,5,6,7,8,9,10]
lista = []
for element in bla:
if element == a:
lista.append(element)
else:
lista.append('not found')
print lista
This way - the return is 10 times - 'not found' - and I need it only one time. lista = ['not found'] Any ideas?
Upvotes: 0
Views: 152
Reputation: 13498
Use python's built in lst.count()
a = 11
bla = [1,2,3,4,5,6,7,8,9,10]
# get number of times a occurs in bla
cnt = bla.count(a)
# if cnt isn't zero then lista becomes a repeated cnt times, otherwise just not found
lista = [a] * cnt if cnt >= 1 else ["not found"]
print(lista)
>>>["not found"]
Edit:
Jean-François Fabre suggested are more pythonic version for building lista
:
lista = [a] * cnt or ["not found"]
Edit 2:
If you want to do something similar for dictionaries you only have to implement the count function for yourself. I turned user into a string literal since making it a list and doing user[0]
each time is pointless:
user = 'john'
user_details = [{u'UserName': u'fred', u'LastSeen': u'a'}, {u'UserName': u'freddy', u'LastSeen': u'b'}]
# get the count
cnt = sum(i['UserName'] == user for i in user_details)
#do what we did before
lista = [user] * cnt or ["not found"]
Edit 3:
Finally if you want to use a for loop, check if it's not found at the end instead of at each step:
user = ['john']
user_details = [{u'UserName': u'fred', u'LastSeen': u'a'},{u'UserName': u'freddy', u'LastSeen': u'b'}]
lis = []
for element in user_details:
if element['UserName'] == user[0]:
lis.append(element)
if not lis: lis.append("not found")
Upvotes: 0