【问题标题】:How to find exact location of a word in list of lists in python(find_word_horizontal)如何在python列表中找到单词的确切位置(find_word_horizo​​ntal)
【发布时间】:2017-08-01 16:15:38
【问题描述】:

我有一个列表列表:

my_list=[['d','c','d','o','g','q'],
            ['c','c','u','c','m','w'],
            ['x','c','c','a','t','t'],
            ['t','c','e','t','k','e']]

word='cat'

我想找到单词[0] 的位置并将其作为列表返回: word[0]='c',所以我的函数应该返回这个:

[2,2]...

如果我的话是'dog',我的函数会返回:

[0,2]...

我有以下代码,但它不起作用。

def find_word_horizontal(my_list, word):
    r=[]
    for row in my_list:
        x = "".join(row)
        s=x.find(word)
        if s != -1:
            a=my_list.index(row)
            r.append(a)
            b=x.index(word[0])
            r.append(b)
    return r

返回:[2,1] 用于 'cat' 而不是 [2,2] 和 [0,1] 用于 'dog' 而不是 [0,2]

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    我认为您代码中的问题出在这一行:

    b=x.index(word[0])
    

    应该是:

    b=x.index(word)
    

    【讨论】:

      【解决方案2】:
      def find_word_horizontal(my_list, word):
          r=[]
          for row in my_list:
              x = "".join(row)
              s=x.find(word)
              if s != -1:
                  a=my_list.index(row)
                  r.append(a)
                  b=x.index(word)
                  r.append(b)
          return r
      

      【讨论】:

        猜你喜欢
        • 2017-09-07
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2017-06-27
        • 2017-01-26
        • 1970-01-01
        • 2021-01-24
        • 2022-07-06
        相关资源
        最近更新 更多