繁体   English   中英

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

[英]How to find string from a list of strings with a specific list of characters?

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

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

这可能会稍微清理你的代码,我认为这是你想要的......

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:list indices必须是整数或切片,而不是list

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

检查一下。

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)

暂无
暂无

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

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