简体   繁体   中英

How to sort a string of email addresses to a list

I want to sort a string that contains email addresses to a list of email addresses. The code gets stuck and nothing happens.

unsorted = "sge@grg.lt ggrge@yahoo.com"
def sort_thatstring():
    s = ""
    out = []
    for x in unsorted:
        s = ""
        while x != " ":
            s+=str(x)
        else:
            out.append(s)
sort_thatstring()
print out

I would like to get:

out = ["sge@grg.lt", "ggrge@yahoo.com"]

You can do:

sorted_list = sorted(unsorted.split(), key=lambda x: x.split('@')[1])

print(sorted_list)
#['sge@grg.lt', 'ggrge@yahoo.com']

Your code has two issues:

You reset s every time you loop in the for loop causing you to loose the data you have read.

The while statement also constructs a loop, but you are using it like an if. Try replacing while with if and read up on the difference between conditionals and loop constructors.

Your function also needs to return the out array otherwise it will be destroyed as soon as your function reaches the end.

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