Reputation: 1280
I want to sort a string that contains email addresses to a list of email addresses. The code gets stuck and nothing happens.
unsorted = "[email protected] [email protected]"
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 = ["[email protected]", "[email protected]"]
Upvotes: 1
Views: 1518
Reputation: 5332
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.
Upvotes: 2
Reputation: 58965
You can do:
sorted_list = sorted(unsorted.split(), key=lambda x: x.split('@')[1])
print(sorted_list)
#['[email protected]', '[email protected]']
Upvotes: 4