[英]Checking if an item is in a list of lists
I am making a password saver and I have a pre-determined list of lists for testing purposes which is:我正在制作密码保护程序,并且我有一个用于测试目的的预先确定的列表列表,它是:
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]]
I give the user a number of choices.我给用户多种选择。 Choice #2 gives them the option to lookup a password
选项 #2 为他们提供了查找密码的选项
if choice == '2': # Lookup a password
print("Which website do you want to lookup the password for?")
for keyvalue in passwords:
print(keyvalue[0])
passwordToLookup = input()
What I need to figure out is:我需要弄清楚的是:
Using filter , it is possible to select the matching element(s) in the list.使用filter ,可以在列表中选择匹配的元素。
Using a list comprehension, select the second element (password) of each.使用列表理解,选择每个元素的第二个元素(密码)。
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]]
website_to_lookup = input()
[e[1] for e in filter(lambda i:i[0]==website_to_lookup,passwords)]
And if you have more than one password per website, use slicing to return them all: [e[1:] for e in filter(lambda i:i[0]==website_to_lookup,passwords)]
如果每个网站有多个密码,请使用切片返回所有密码:
[e[1:] for e in filter(lambda i:i[0]==website_to_lookup,passwords)]
Python makes many things easy and one of them is iterating through a list(or Iterator) Python 使许多事情变得简单,其中之一是遍历列表(或迭代器)
Suppose this is your list of list:假设这是您的列表列表:
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"], ['StackOverflow','uesodsiom'], ['Facebook', 'sdhf9wk']]
You can iterate through a list like this:您可以遍历这样的列表:
for lst in passwords:
print(lst)
['yahoo', 'XqffoZeo']
['google', 'CoIushujSetu']
['StackOverflow', 'uesodsiom']
['Facebook', 'sdhf9wk']
You did not need range or len in this case, although they could be useful in other cases.在这种情况下,您不需要 range 或 len,尽管它们在其他情况下可能很有用。
What if you only wanted a single element of the nested list that is your website?如果您只想要嵌套列表中的一个元素,即您的网站,该怎么办? Then you could just index:
然后你可以索引:
for lst in passwords:
print(lst[0])
yahoo
google
StackOverflow
Facebook
If you wanted the passwords, use lst[1].如果需要密码,请使用 lst[1]。 The indexing starts from 0.
索引从 0 开始。
Note the structure of your list should remain the same: first element is the website name and the second element is the password.请注意,您的列表结构应保持不变:第一个元素是网站名称,第二个元素是密码。
Now, from my understanding you want to check if given a website, it matches a password现在,根据我的理解,您想检查是否给定了一个网站,它是否与密码匹配
First method:第一种方法:
website = 'Facebook'
passwordToLookup = 'sdhf9wk'
for lst in passwords:
if lst[0] == website and lst[1] == passwordToLookup:
print(True)
True
Second Method where you are unpacking each element in the list of passwords:解压密码列表中的每个元素的第二种方法:
for websi, password in passwords:
if websi == website and password == passwordToLookup:
print(True)
True
Unpacking example:开箱示例:
x, y = [1, 2]
print(x)
1
print(y)
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.