J French
J French

Reputation: 197

Is there a better way I can apply the count function to two sets of lists?

I have two binary lists, is there a better way of assigning the binary list containing more 1's to the variable moreOnes? Bellow is my attempt.

    moreOnes = []
    for i in len(list1):
      if list1.count(1) > list2.count(1):
        moreOnes = list1
      else:
        moreOnes = list2

Upvotes: 1

Views: 35

Answers (2)

Alexander Golys
Alexander Golys

Reputation: 703

You can use max function with lambda expression as a key:

moreOnes = max(list1, list2, key=lambda x: x.count(1))

Upvotes: 1

Zach Peltzer
Zach Peltzer

Reputation: 172

If you want the list with more 1's, you don't need that loop, just the if statement inside. If you want it more succinct, you could also do:

moreOnes = list1 if list1.count(1) > list2.count(1) else list2

Upvotes: 1

Related Questions