python - 如果存在重复值,如何返回 True 和 false
问题描述
我有一个清单:
list = ["A", "A", "B", "A", "C"]
和一个for
和if
语句相结合:
for x in list:
if "A" in x:
print("true")
上述代码的输出:
true
true
接下来,我正在弄清楚如何告诉我"A"
列表中有重复项并返回我的值True
这是我尝试过的:
for x in list:
if any(x == "A" in x):
return True
但出现错误:
SyntaxError: 'return' outside function
也试过这个:
for x in list:
if any(x == "A" in x):
return True
SyntaxError: expected an indented block
我想要的输出是:
True
因为"A"
存在的重复项
解决方案
可以使用Counter
:
from collections import Counter
# hold in a 'dictionary' style something like: {'A':2, 'B':1, 'C':2}
c = Counter(['A','A','B', 'C', 'C'])
# check if 'A' appears more than 1 time. In case there is no 'A' in
# original list, put '0' as default.
c.get('A', 0) > 1 #
>> True
推荐阅读
- php - Merge multiple arrays into one with unique values php
- https - 没有 HTTPs 的 ASP.NET Core 2.1 个人用户帐户
- php - PHPExcel - 而不是下载保存到目录
- mysql - 使用一个查询更新架构内所有表中的列
- calculated-columns - Spotfire,用另一个计算列的绝对值填充空/空白单元格
- visual-studio - msvc 不使用 CMake automoc 生成 moc 文件
- javascript - 如果用户跳过反应 js 中的字段,如何为非必需输入添加空值
- angular - 元素上的角度,多个双重类删除1
- jquery - 如何限制DataTable单个单元格中的数据
- c++ - Linux 上 Eclipse cdt 的 CMake 项目生成器?