In C#, if I have a collection of strings, and I want to get a comma-separated string representing of the collection (without extraneous comments at the beginning or end), I can do this:
string result = collection.Aggregate((s1, s2) => String.Format("{0}, {1}", s1, s2));
I could do something like
result = collection[0]
for string in collection[1:]:
result = "{0}, {1}".format(result, string)
But this feels like a cludge. Does python have an elegant way to accomplish the same thing?
Use str.join
:
result = ', '.join(iterable)
If not all the items in the collection are strings, you can use map
or a generator expression:
result = ', '.join(str(item) for item in iterable)
The Equivalent of the C# Enumerable.Aggregate method is pythons built in "reduce" method. For example,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
Calculates ((((1+2)+3)+4)+5). which is 15
This means you could achieve the same with
result = reduce(lambda s1, s2: "{0}, {1}".format(s1, s2), collection)
Or with
result = reduce(lambda s1, s2: s1 + ", " + s2, collection)
In your Case it would be better to use ', '.join
as others have suggested because of pythons immutable strings.
For completeness the C# Enumerable.Select method in python is "map".
Now if anyone asks you can say you know MapReduce :)
You could do something like:
> l = [ 1, 3, 5, 7]
> s = ", ".join( [ str(i) for i in l ] )
> print s
1, 3, 5, 7
I suggest looking up "python list comprehensions" (the [ ... for ... ] in the above) for more info.
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.