我使用RE在列表中搜索,但得到了一个类型不匹配的错误,我无法找出。这是全部代码。我检查了r的类型,它以regex的形式出现,我假设它与字符串一起工作,因为我在堆栈溢出中发现了这个位
import re
i = int(input())
l = []
k = []
for j in range(i):
l.append(int(input()))
for a in l:
n = int(a)
hd = 0
ld = 9
while n > 0:
rn = n % 10
if hd < rn:
hd = rn
if ld > rn:
ld = rn
n = int(n / 10)
x = hd*11 + ld*7
if x > 99:
x = x - 100
k.append(x)
cn = 0
r = re.compile("1[0-9]+")
nl = list(filter(r.search, k))
if len(nl) == 2 :
cn = cn + 1
type(r)
elif len(nl) > 2:
cn = cn + 2
我得到这个错误:
Traceback (most recent call last):
File "<ipython-input-13-5ea828f5282e>", line 36, in <module>
nl = list(filter(r.search, k))
TypeError: expected string or bytes-like object
Traceback (most recent call last):
File "<ipython-input-13-5ea828f5282e>", line 36, in <module>
nl = list(filter(r.search, k))
TypeError: expected string or bytes-like object
正如错误消息所说,您的列表不包含字符串。您可以使用
str(number)
将数字转换为字符串,然后对结果进行正则表达式匹配,但在这种情况下,一个更简单、更有效的过滤器是过滤掉10以下的数字(我猜这也将允许您完全放弃对re
的依赖性)相关问题 更多 >
编程相关推荐