所以我有一个清单
myList = [["hello my name is john"],["hey my name is john"],["hello my name is smith"]]
我希望用户能够搜索hello
并输出
"hello my name is john"
"hello my name is smith"
或搜索john
,输出为
"hello my name is john"
"hey my name is john"
我目前的代码没有任何输出
def pattern():
search = input("Search: ")
match = [word for word in myList if search in word]
for confirmedMatch in match:
print(confirmedMatch)
pattern()
我做错了什么?
答案 0 :(得分:4)
问题在于你的清单。
如果您的列表是字符串列表而不是列表列表,则代码有效。
myList = ["hello my name is john","hey my name is john","hello my name is smith"]
鉴于您的初始解决方案,它会检查"你好"是列表中的元素。您希望它检查它是否是字符串的子字符串。
如果您希望它使用列表列表,那么
行 match = [word for word in myList if search in word]
变为
match = [word for word in myList if search in word[0]]
(假设内部列表只有一个元素)