python - How to find string from a list of strings with a specific list of characters?
问题描述
I have a given list of string and a list of characters and I want to check the string with containing a specific character. Here is an example:
Dictionary = ["Hello", "Hi"]
Character = ['e','i']
it must return a "Hello" else empty list
I am comparing a list of characters with a list of strings but it is giving me a type error.
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):
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)
推荐阅读
- php - 安装问题
- python - 是否可以创建一个带有可以接受各种形式的键的python字典?
- javascript - 为什么 Webpack 不能解析 'babel-loader'?
- docker - 在 Alpine 映像上运行 dotnet core 2.1 应用程序时出错
- windows - 如何修复 Windows 上 WxPython 控件中的模糊文本?
- javascript - 为什么节点打印未定义而浏览器没有?
- node.js - 如何从条带令牌正确创建条带源
- asp.net - C# iTextSharp PdfCopy to MemoryStream 复制整个文档和单页
- javascript - 使用 JavaScript 在 HTML 表格中添加行
- java - 两个 DateTime 对象之间的差异(以分钟为单位)