python - 简单的 python 2.7 代码有某种问题 : "' list' object has no attribute 'find' "

标签 python string python-2.7 list dictionary

此代码的目的是返回一个字典,其中列出了较大字符串中子字符串的起始索引。

例如。 matchUp(["a", "b, "c", "d"], "abc") 将返回:{"a":0, "b":1, "c":2, "d":- 1}(-1 是默认的空键)

这个问题的提示是 find 函数可以告诉你另一个字符串中子字符串的起始索引。这是正确的语法,对吧?我的字符数组位于 strArray 中,y 是我正在搜索的子字符串。

def matchUp (strArray, word):
    index ={}
    for x in strArray:
        index [x]=-1
    for y in word:
       for x in index:
           if y in strArray:
              index [x]= strArray.find(y)

    return index 

最佳答案

您需要调用word.find,而不是strArray.find

def matchUp (strArray, word):
    index = {}
    for ch in strArray:
        index[ch] = word.find(ch)  # <---
    return index

(无需使用嵌套循环)

使用示例:

>>> matchUp(["a", "b", "c", "d"], "abc")
{'a': 0, 'c': 2, 'b': 1, 'd': -1}

关于python - 简单的 python 2.7 代码有某种问题 : "' list' object has no attribute 'find' ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40571387/

相关文章:

javascript - Python "print"不记录到 Forever.js 日志

python - Django AttributeError 'ModelFormOptions' 对象没有属性 'concrete_fields'

Javascript 正则表达式在不使用引号时按单词边界拆分字符串

python - 筛选比较,计算相似度得分,python

java - 使用带小数的 string.split() - 不起作用

C++ .length() 函数给出错误的结果

python - 使用触觉开关重新启动 Python 脚本

python - python中的错误文本编码

python - 如何派生带有修饰方法的类?

python - 一起添加字典