简体   繁体   English

如何解决“ TypeError:字符串索引必须为整数”错误?

[英]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

In the code above, I have a string s = "abcaccba" (say) and I have an array of indices, queries = [1, 3, 2] . 在上面的代码中,我有一个字符串s =“ abcaccba”(例如),并且有一个索引数组,querys = [1、3、2 [1, 3, 2] I am trying to find the closest occurrence of the character at these indices. 我正在尝试在这些索引处找到最接近的字符。

For example: s[1] = b and the closest index at which the second occurrence of b is, is at 6. When I try to run the code above, I get this error: 例如: s[1] = b ,第二个b出现的最接近的索引是6。当我尝试运行上面的代码时,出现以下错误:

File "solution.py", line 23, in closest
    if s[i] == c:
TypeError: string indices must be integers

What am I doing wrong here?? 我在这里做错了什么?

i already a character in string. i已经是字符串中的字符了。 You just need to change s[i] to i and calculate the position of character. 您只需要将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)

The error you are getting is because i is a string but indexes must be integers . 您得到的错误是因为i是一个string但是索引必须是integers (This should be clear from the error message). (这应该从错误消息中清除)。 Changing the piece if s[i] ==c: to if i == c: would make your code run but I do not think it will give you the answer you are really looking for. if s[i] ==c:更改为if i == c: ,将使您的代码运行,但是我认为这不会给您真正想要的答案。

Since you want the closest index in which the character is the same as that of the index of the query, I think you should get as a list of results which should be as long as the len gth of your queries . 既然你想最接近的索引中的字符是相同查询的指标,我认为你应该得到的结果应该是,只要名单len您的GTH queries Below is some code that can help you achieve that goal. 以下是一些可以帮助您实现该目标的代码。 I have also extended your example to enhance understanding. 我也扩大了您的榜样,以增进理解。

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) 

Here is the output 这是输出

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')]

You can use the find() string method to look up character positions in a string. 您可以使用find()字符串方法来查找字符串中的字符位置。

Look at the string segments ahead and behind of each query -indexed character. 查看每个query索引字符前后的字符串段。 Then use their relative position to determine their true index in s . 然后使用它们的相对位置来确定它们在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]

I added an additional edge case, z , to cover the case where there are no additional instances of that character. 我添加了一个额外的边缘情况z ,以涵盖该字符没有其他实例的情况。 In that case, the procedure returns None . 在这种情况下,过程将返回None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM