', '.join(l)
time-(and sanity-) saver, here's the answer to the Oh no! it's a list of strings and not some other random objects that I need! disaster.The problem is simple: I have a list of non-string objects, but the operation I want to perform on them requires a list of strings. Naively I break out the dreaded conversion loop:
num_list = [1, 2, 3, 4]
str_list = []
for item in num_list:
str_list.append( str(item) )
Bah! Three lines of code! Whatta waste!
Python to the rescue with the line-saving
map
function:
map(str, num_list)
And we're done.
The map function takes a function and a list, and applies that function to each element of the list, so it is useful for much more than just string magic.
So, to print the list of ints above, separated by commas:
', '.join( map(str, num_list) )
No comments:
Post a Comment