【问题标题】:How do I print values only when they appear more than once in a list in python仅当它们在python列表中出现多次时如何打印值
【发布时间】:2019-11-26 08:35:30
【问题描述】:

我有以下清单:

seqList = [0, 6, 1, 4, 4, 2, 4, 1, 7, 0, 4, 5]

我只想在列表中的项目出现多次时打印(在本例中为值 1 和 4),并且我想忽略列表中的第一个值(在本例中为值 0)

要计算每个值在列表中出现的次数,我有以下代码:

from collections import Counter

seqList = [0, 6, 1, 4, 4, 2, 4, 1, 7, 0, 4, 6]

c = dict(Counter(seqList))
print(c)

带输出:

{0: 2, 6: 1, 1: 2, 4: 4, 2: 1, 7: 1, 5: 1}

但我想忽略除 1 和 4 之外的所有内容,并且列表中的第一个 0 不应该计算在内。

我要打印的输出是:

-value 1 appears multiple times (2 times)
-value 4 appears multiple times (4 times)

有人知道我如何实现这一目标吗?

【问题讨论】:

  • 这是个好问题!它显示了清晰的示例和预期的输出。
  • 谢谢 :) 我花了 30 分钟写得尽可能准确。

标签: python list


【解决方案1】:

您可以进行以下调整:

c = Counter(seqList[1:])  # slice to ignore first value, Counter IS a dict already 

# Just output counts > 1
for k, v in c.items():
    if v > 1:
        print('-value {} appears multiple times ({} times)'.format(k, v))

# output
-value 1 appears multiple times (2 times)
-value 4 appears multiple times (4 times)

【讨论】:

    【解决方案2】:

    一个很好的带有列表理解的单行代码如下所示:

    [print(f'- value {k} appears multiple times ({v} times)') for k, v in c.items() if v > 1]
    

    【讨论】:

    • 不要对副作用使用列表推导
    • 虽然它部分工作,但它并没有忽略第一个元素。我们可以删除第一个元素或忽略它。更好的 c = dict(Counter(seqList[1:])) 忽略计数器中的第一个元素
    猜你喜欢
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多