[英]Python: check if string is in any items in a list?
I have a server_list
and I am parsing email addresses from a file. 我有一个server_list
并且正在从文件中解析电子邮件地址。 I want to collect all addresses that are not from certain servers eg gmail.com. 我想收集并非来自某些服务器(例如gmail.com)的所有地址。
Currently I have this inside the file reading loop: 目前,我在文件读取循环中包含以下内容:
server_list = ["gmail.com", "yahoo.com"] #etc
for servers in server_list:
if servers in emailaddress: #get emailaddress from inside of a open(file) line loop
badmail.extend(emailaddress)
This allows me to collect the bad emails in a list badmail
. 这使我可以在列表badmail
收集不良电子邮件。 Is there any way to create a list of good emails ie if emailaddress
is not contained in any items in server_list
in the same loop or do I have to create a list of all emails and remove the bad emails? 有什么方法可以创建一个好邮件列表,例如,如果在同一循环的server_list
中的任何项中都不包含emailaddress
还是必须创建所有电子邮件的列表并删除不良电子邮件?
You can use all
function to make sure that the emailaddress doesn't end with any of the servers in the server_list
, like this 您可以使用all
函数来确保emailaddress不以server_list
中的任何服务器结尾,例如
server_list, good_email = ["gmail.com", "yahoo.com"], []
if all(not emailaddress.endswith(server) for server in server_list):
good_email.append(emailaddress)
The same way, you can use any
function to get the bad email address, like this 同样,您可以使用any
功能来获取错误的电子邮件地址,如下所示
server_list, bad_email = ["gmail.com", "yahoo.com"], []
if any(emailaddress.endswith(server) for server in server_list):
bad_email.append(emailaddress)
Looks like you are reading the email addresses from a file. 看起来您正在从文件中读取电子邮件地址。 So, you can do something like this 所以,你可以做这样的事情
server_list, good_list, bad_list = ["gmail.com", "yahoo.com"], [], []
with open("email.txt") as in_file:
for email_address in in_file:
email_address = email_address.rstrip()
if any(email_address.endswith(server) for server in server_list):
bad_list.append(email_address)
else:
good_list.append(email_address)
As per lvc
's suggestion , we can actually pass a tuple of data to str.endswith
. 根据lvc
的建议 ,我们实际上可以将一元数据传递给str.endswith
。 So, the code can be further simplified to 因此,代码可以进一步简化为
server_list, good_list, bad_list = ("gmail.com", "yahoo.com"), [], []
...
...
if email_address.endswith(server_list):
bad_list.append(email_address)
else:
good_list.append(email_address)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.