有没有更好的方法可以将count函数应用于两组列表?

我有两个二进制列表,是否有更好的方法将包含更多1的二进制列表分配给变量moreOnes?贝娄是我的尝试。

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

评论
ased
ased

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
点赞
评论
Tracy
Tracy

您可以将max函数与lambda表达式一起用作键:

moreOnes = max(list1, list2, key=lambda x: x.count(1))
点赞
评论