2

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?

Matthew
  • 28,056
  • 26
  • 104
  • 170
  • 1
    Your C# code has horrible performance also (compared to how you *could* do it), so I wouldn't worry too much about it since it seems good enough for you... – Blindy Sep 28 '11 at 16:40
  • @Blindy, yeah I realized that right after I posted, and removed that part of my question :) – Matthew Sep 28 '11 at 16:42
  • It might be helpful to include an example of input and output, but it sounds like you can use reduce() as a drop in replacement for collection.Aggregate(), but there are other alternatives. – Austin Marshall Sep 28 '11 at 16:44
  • 1
    Lots of potential duplicates for this, one is [Python: how to join entries in a set into one string?](http://stackoverflow.com/questions/7323782/python-how-to-join-entries-in-a-set-into-one-string) – agf Sep 28 '11 at 16:45

3 Answers3

7

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)
agf
  • 171,228
  • 44
  • 289
  • 238
4

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 :)

lee penkman
  • 1,160
  • 15
  • 19
0

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.

Joe
  • 1
  • 1. He did say it's a collection of strings so the `str` part is not really necessary. 2. Even if you do use `str`, a list comprehension is not the right tool, use a generator expression. 3. Please don't post answers that just replicate the solution shown in another answer. – agf Sep 28 '11 at 16:51