【问题标题】:How do I resolve "TypeError: string indices must be integers" error?如何解决“TypeError:字符串索引必须是整数”错误?
【发布时间】:2018-10-13 00:27:03
【问题描述】:
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"(比如说),我有一个索引数组,查询 = [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 中的一个字符,而不是整数。
  • 试试for i in range(len(s[query:])):
  • @Varun,当我尝试它给我另一个错误:TypeError:'int' object is not iterable
  • 不清楚您希望该函数做什么。与这些参数对应的预期输出是什么?
  • @PM2Ring,在上面的示例中:我希望输出 6、3 和 4 作为索引 1、3 和 2 处字符 b、a 和 c 最接近出现的索引

标签: python arrays string indexing


【解决方案1】:

您可以使用find() 字符串方法来查找字符串中的字符位置。

查看每个query-indexed 字符前后的字符串段。然后使用它们的相对位置来确定它们在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

【讨论】:

    【解决方案2】:

    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)
    

    【讨论】:

      【解决方案3】:

      您得到的错误是因为istring,但索引必须是integers。 (这应该从错误消息中清楚地看出)。将 if s[i] ==c: 更改为 if i == c: 将使您的代码运行,但我认为它不会为您提供您真正想要的答案。

      由于您想要字符与查询索引相同的最接近的索引,我认为您应该得到一个结果列表,该列表应该与您的 @987654327 的 length 一样长@。下面是一些可以帮助您实现该目标的代码。我还扩展了您的示例以增强理解。

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

      【讨论】:

      • 对不起@Rabbid76,我误按了回复按钮。我现在已经发布了我的答案。
      猜你喜欢
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 2016-08-26
      相关资源
      最近更新 更多