简体   繁体   中英

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. I want to collect all addresses that are not from certain servers eg 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 . 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?

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

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

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 . 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM