【问题标题】:Not counting empty list while counting total lists count in Python [duplicate]在计算Python中的总列表计数时不计算空列表[重复]
【发布时间】:2018-09-04 07:13:00
【问题描述】:

我有 3 个列表,其中 1 个为空。我想计算列表中不为空的列表。

例如:

 a = ['username', 'username', 'social']
 b = []
 c = ['username', 'instead', 'added']

将所有列表组合在一起:

combine = [a,b,c]

计算非空列表:

count = sum(x is not '' for x in combine)

当我运行上述代码时,我得到 'count=3' 但我想要 'count=2'

请帮助我如何做到这一点。

【问题讨论】:

  • 您为什么认为[] == '' 是一个空列表?
  • 好的,所以在这种情况下,我不想计算 [] 并计算休息时间。
  • 你应该可以做到sum(map(bool, combine))sum(bool(x) for x in combine)
  • 感谢@cᴏʟᴅsᴘᴇᴇᴅ 它对我有用。
  • 这是另一个尝试len(list(filter(None, combine))

标签: python list


【解决方案1】:

试试

count =sum(len(x)>0 for x in combine)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-04
    • 2017-11-28
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2015-05-14
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多