如何在列表中使用count()方法,不包括某些项目

时间:2014-10-27 20:29:04

标签: python list python-3.x count

所以,我想如果在列表中有任何重复的数字,但我想排除其中的一些。我怎么能用count()方法呢?我可以吗?

示例:

thelist = [0,0,3,4]

for x in thelist:
    if thelist.count(x) > 1:
            print("Repeated")
            break

显然它反复说。现在,我怎样才能避免计算零?我只是想要计算以下数字:

only_numbers_the_function_should_test = [1,2,3,4]

我在网上搜索过,一无所获。也许这是不可能的。你能给我一个替代方案吗?

注意:我不希望它删除任何列表项。这是一个数独求解器。我无法削减这样的数字。

2 个答案:

答案 0 :(得分:1)

坚持if条件。

for x in thelist:
    if x==0:
        continue
    # rest of your code

或者如果你想要一个特定的范围:

if x <= 0 or x > 9:
    continue

答案 1 :(得分:1)

为什么不首先从列表中过滤0,然后计算:

from collections import Counter
thelist = [0, 0, 3, 4]
counter = Counter([x for x in l if x != 0])
for i in Counter([x for x in thelist if x != 0]):
    if counter[i] > 1:
        print("Repeated")

编辑:只需对代码进行简单修改

thelist = [0,0,3,4]

for x in [x for x in thelist if x != 0]:
    if thelist.count(x) > 1:
       print("Repeated")
       break