如何从具有特定字符列表的字符串列表中查找字符串?

时间:2019-03-22 19:50:37

标签: python python-3.x

我有给定的字符串列表和字符列表,我想检查包含特定字符的字符串。这是一个示例:

Dictionary = ["Hello", "Hi"]
Character = ['e','i']

它必须返回一个“ Hello”,否则为空列表

我正在比较一个字符列表和一个字符串列表,但这给了我一个类型错误。

Dictionary = ["Hello", "Hi"]
Character = ['e']
emptystring = ""
def findwords(dictionary,character):
   for i in dictionary,character:
      for j in dictionary:
          if character[i] == dictionary[i][j]:
             return dictionary[i]
          else:
             j+=1
    i+=1
return emptystring

k = findwords(Dictionary,Character)
k

TypeError                                 Traceback (most recent call last)
<ipython-input-49-996912330841> in <module>
----> 1 k = findwords(Dictionary,Character)
      2 k

<ipython-input-48-9e9498ec1a51> in findwords(dictionary, character)
      5     for i in dictionary,character:
      6         for j in dictionary:
----> 7             if str(character[i]) == str(dictionary[i][j]):
      8                 return str(dictionary[i])
      9             else:

TypeError: list indices must be integers or slices, not list

2 个答案:

答案 0 :(得分:0)

这可能会清理您的代码,我想这就是您想要的...

Dictionary = ["Hello", "Hi"]
Character = ["e"]


def findwords(dictionary, character):
    for i in dictionary:
        if any(j in i for j in character):
            return i
    return ""

对于所有比赛:

def findwords(dictionary, character):
    matches = []
    for i in dictionary:
        if any(j in i for j in character):
            matches.append(i)
    if matches:
        return ",".join(matches)
    else:
        return ""

它将查看子字符串中是否有任何单词与您的单词匹配。如果是,则返回单词,否则返回""

  

findwords([“ Hello”,“ Hi”],[“ e”])

     

“你好”

     

findwords([“ Hello”,“ Hi”],[“ k”])

     

''

对于您的问题:

  

TypeError:列表索引必须是整数或切片,而不是列表

   for i in dictionary,character: <-- I will be list ['Hello', 'Hi']
      for j in dictionary:
          if character[i] == dictionary[i][j]:  <---- you can't do character[i] where i is ['Hello', 'Hi']

答案 1 :(得分:0)

检查。

Dictionary = ["Hello", "Hi"]
Character = ['e']

def findwords(dictionary,character):
    tmp = ""
    for i in dictionary:
        #convert string to char list
        str_arr = list(i)
        for j in character:
            #if char is in char list then save it in tmp variable
            #if you want multiple values then use array instead of tmp
            if j in str_arr:
                tmp = i
    return tmp

k = findwords(Dictionary,Character)
print(k)