python-3.x - 计数(在范围内) TypeError Python

标签 python-3.x

我收到以下错误

'TypeError: must be str, not generator'.

下面的代码

a = '0123456789 01234 01234567890 6789012345 012322456789'
b = a.split(" ")
for num in b:
    if num.count(**i for i in range(10)**) <= 1:
        print("True")
    else:
        print("False")

上面应该检查每个数字是否有重复的数字(False)或没有(True)。

例如,第一个数字 0123456789 返回 True,因为它没有任何重复的数字。

另一方面,最后一个数字012322456789返回False,因为它有三个“2”。

最佳答案

您不能将 .count() 与多个参数一起使用。将您的条件更改为:

if all(num.count(str(i)) <= 1 for i in range(10)):

这将根据字符串测试每个数字,如果所有重复 1 次或 0 次,则返回 True。

您还可以仅测试 num 中的数字,而不是使用 09 中的每个数字:

if all(num.count(i) == 1 for i in num):

或使用set来测试唯一性:

if len(set(num)) == len(num):

关于python-3.x - 计数(在范围内) TypeError Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58847862/

相关文章:

python - 导入错误 : No module named pip when trying to install packages

python-3.x - 多个相同进程的 Gunicorn 高内存使用率?

python - 我如何使用矢量来实现与此相同的效果

python-3.x - 在 python 中创建 http 服务器时代码 501,消息不支持的方法 ('GET' )

python - python 中导入错误

python - 根据 YAML 文件中的用户输入将自定义字段添加到 JSON 文件 - Python3

python-3.x - 模块未找到错误 : No module named '_sqlite3'

python - 如何使用 pyo3 从 Python 文件中调用 Rust 函数?

python - 无法让角色改变颜色

python - 使用 del 或 pop() 来简单地删除一个值是否正确?