简体   繁体   English

如何将电子邮件地址字符串排序到列表

[英]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. 每次在for循环中循环时,都会重置s,从而导致丢失已读取的数据。

The while statement also constructs a loop, but you are using it like an if. while语句还构造了一个循环,但是您像if一样使用它。 Try replacing while with if and read up on the difference between conditionals and loop constructors. 尝试用if代替while并阅读条件和循环构造函数之间的区别。

Your function also needs to return the out array otherwise it will be destroyed as soon as your function reaches the end. 您的函数还需要返回out数组,否则一旦函数到达末尾,它将被销毁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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