我收到以下错误
'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
中的数字,而不是使用 0
到 9
中的每个数字:
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/