[英]I'm getting this error --> TypeError: string indices must be integers
[英]How do I resolve “TypeError: string indices must be integers” error?
def closest(s, queries):
for query in queries:
c = s[query]
for i in s[query:]:
if s[i] == c:
return i
else:
return -1
在上面的代码中,我有一个字符串s
=“ abcaccba”(例如),并且有一个索引数组,querys = [1、3、2 [1, 3, 2]
。 我正在尝试在这些索引处找到最接近的字符。
例如: s[1] = b
,第二个b出现的最接近的索引是6。当我尝试运行上面的代码时,出现以下错误:
File "solution.py", line 23, in closest
if s[i] == c:
TypeError: string indices must be integers
我在这里做错了什么?
i
已经是字符串中的字符了。 您只需要将s[i]
更改为i
并计算字符的位置即可。
def closest(s, queries):
for query in queries:
c = s[query]
for i in s[query:]:
if i == c: # i is a char , i = s[position]
print( i,(s[query+1:].index(i)+query+1) )
break
else:
pass
s = "abcaccba"
queries = [1, 3, 2]
closest(s, queries)
您得到的错误是因为i
是一个string
但是索引必须是integers
。 (这应该从错误消息中清除)。 if s[i] ==c:
更改为if i == c:
,将使您的代码运行,但是我认为这不会给您真正想要的答案。
既然你想最接近的索引中的字符是相同查询的指标,我认为你应该得到的结果应该是,只要名单len
您的GTH queries
。 以下是一些可以帮助您实现该目标的代码。 我也扩大了您的榜样,以增进理解。
s = "abcaccba"
queries = [1,3,2,0, 5]
def closest(s, queries):
print('String: ', s)
print('Query: ', queries)
results = []
for query in queries:
c = s[query]
if s[query] in s[query+1 :]:
results.append(('query = {}'.format(query), 'character = {}'.format(c), 'index of next occurrence = {}'.format(1+query+s[query+1 :].index(c))))
#results.append((query, c, 1+query+s[query+1 :].index(c)))
else:
results.append(('query = {}'.format(query), 'character = {}'.format(c), 'index of next occurrence = {}'.format(-1)))
#results.append((query, c, -1))
return results
closest(s = s, queries = queries)
这是输出
String: 'abcaccba'
Query: [1, 3, 2, 0, 5]
[('query = 1', 'character = b', 'index of next occurrence = 6'),
('query = 3', 'character = a', 'index of next occurrence = 7'),
('query = 2', 'character = c', 'index of next occurrence = 4'),
('query = 0', 'character = a', 'index of next occurrence = 3'),
('query = 5', 'character = c', 'index of next occurrence = -1')]
您可以使用find()
字符串方法来查找字符串中的字符位置。
查看每个query
索引字符前后的字符串段。 然后使用它们的相对位置来确定它们在s
的真实索引。
s = "abcaccbaz"
queries = [1, 3, 2, 0, 5, 6, 8]
closest = []
for q in queries:
char = s[q]
pre = s[:q][::-1] # reversed, so nearest character to char is first
post = s[q+1:]
pre_dist = pre.find(char)
pre_found = pre_dist >= 0
post_dist = post.find(char)
post_found = post_dist >= 0
if post_found and (post_dist <= pre_dist or not pre_found):
closest.append(post_dist + len(pre) + 1)
elif pre_found and (pre_dist <= post_dist or not post_found):
closest.append(q - pre_dist - 1)
else:
closest.append(None)
closest
# [6, 0, 4, 3, 4, 1, None]
我添加了一个额外的边缘情况z
,以涵盖该字符没有其他实例的情况。 在这种情况下,过程将返回None
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.