如何在列表中使用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 个回答
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
1
只需要加一个if条件就可以了。
for x in thelist:
if x==0:
continue
# rest of your code
或者如果你想要一个特定的范围:
if x <= 0 or x > 9:
continue