繁体   English   中英

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

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

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

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

如果你想要更多 1 的列表,你不需要那个循环,只需要里面的if语句。 如果你想让它更简洁,你也可以这样做:

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

您可以使用 max function 和 lambda 表达式作为键:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM