[英]How do I print the list in a list by searching for a specific keyword?
I want to write a python function which will print the list in list by searching for a specific keyword. 我想编写一个python函数,通过搜索特定的关键字将列表中的列表打印出来。 This is my function but it doesn't work. 这是我的功能,但是不起作用。
user_adresses = [["John","Walker","New York","10001"],["Larry","Smith","Denver","80123"]]
def search(user_adresses):
alpha = str(input("What are you searching for? "))
for item in user_adresses:
print(str(item[0:])[1:-1])
The program will ask me what I am searching for, if I type "John" it should only print the list with John -> "John","Walker","New York","10001" 该程序将询问我要搜索的内容,如果键入“ John”,则仅应使用John->“ John”,“ Walker”,“ New York”,“ 10001”打印列表。
But in this way it will me print me all lists. 但是这样我就可以打印所有列表了。 What should be added to the function to print just the list with the specific keyword in it? 应该添加什么功能以仅打印其中带有特定关键字的列表?
Thank you 谢谢
You can check for membership in a list using in
. 您可以使用in
检查列表in
成员身份。 This will match any and all full words that are in the user address. 这将匹配用户地址中的所有完整单词。
for user in user_adresses:
if alpha in user:
print(user)
user_adresses = [["John","Walker","New York","10001"],["Larry","Smith","Denver","80123"]]
def search(user_adresses):
alpha = str(input("What are you searching for? "))
for item in user_adresses:
if alpha in item:
print(item)
Use in
operator to check if the input is in a given item 使用in
运算符检查输入是否在给定项目中
You can express this quite concisely: 您可以非常简洁地表达这一点:
for match in (address in user_addresses if alpha in address):
print(match)
This will print every match, where a 'match' is any 'address' in user_addresses
if the term alpha
occurs in address
. 这将打印每个匹配项,如果“ alpha
出现在address
中,则“ match”是user_addresses
任何“ address”。
This peace of code should work. 代码的这种和平应该起作用。 Consider to use dictionary instead of list. 考虑使用字典而不是列表。
def search(user_addresses):
alpha = input("What are you searching for? ")
for user_address in user_addresses:
if alpha in user_address:
print(user_address)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.