0

I have a simple problem and I couldn't solve it. I have a list;

[9, 0, 3, 0, 0, 0, 2, 0, 6]

If an element in this list is in digits, I want to add 1 to counter variable.

digits = [1,2,3,4,5,6,7,8,9]
lst = [9, 0, 3, 0, 0, 0, 2, 0, 6]

Right now I'm doing it with

digits = [1,2,3,4,5,6,7,8,9]
lst = [9, 0, 3, 0, 0, 0, 2, 0, 6]
counter = 0
for x in lst:
    if x in digits:
        counter += 1

I want to write that for loop as one-liner. I tried

t = counter += 1 for x in lst if x in digits

But not worked as expected. I just stuck, how can I do this?

2
  • @vaultah That is a solution for me yes, but I'm wondering how can I make one-liner loop like [x for x in lst if x in digits] and add 1 to counter variable? I tried counter+=1 for x.... as I wrote in my question but didn't work. Commented May 16, 2016 at 17:11
  • @vaultah could you write these comments as an answer please. Commented May 16, 2016 at 17:19

2 Answers 2

1

You can do this in two possible ways:

  1. List Comprehensions:
counter = len([x for x in lst if x in digits])
  1. The function: filter(function, list) which offers an elegant way to filter out all the elements of a list, for which the function function returns True.
    not_digits = lambda x: x not in digits
    counter = len(filter(not_digits, lst))
Sign up to request clarification or add additional context in comments.

Comments

1

My guess is that you are trying to use a python statement instead of an expression in a list comprehension. This will not work. I think @vaultah provides an excellent solution in his comment.

If you insist on explicit assignment to counter, maybe try reduce:

if 'reduce' not in globals():
    from functools import reduce

counter = 0

digits = [1,2,3,4,5,6,7,8,9]
lst = [9, 0, 3, 0, 0, 0, 2, 0, 6]

counter = reduce(lambda c, d: c + 1 if d in digits else c, lst, counter)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.