3

If you had a long list of lists in the format [['A',1,2],['B',3,4]] and you wanted to combine it into ['A, 1, 2', 'B, 3, 4'] is there a easy list comprehension way to do so?

I do it like this:

this_list = [['A',1,2],['B',3,4]]
final = list()
for x in this_list:
     final.append(', '.join([str(x) for x in x]))

But is this possible to be done as a one-liner?

Thanks for the answers. I like the map() based one. I have a followup question - if the sublists were instead of the format ['A',0.111,0.123456] would it be possible to include a string formatting section in the list comprehension to truncate such as to get out 'A, 0.1, 0.12'

Once again with my ugly code it would be like:

this_list = [['A',0.111,0.12345],['B',0.1,0.2]]
final = list()
for x in this_list:
    x = '{}, {:.1f}, {:.2f}'.format(x[0], x[1], x[2])
    final.append(x)

I solved my own question:

values = ['{}, {:.2f}, {:.3f}'.format(c,i,f) for c,i,f in values]
Ian Fiddes
  • 2,821
  • 5
  • 29
  • 49

3 Answers3

6
>>> lis = [['A',1,2],['B',3,4]]
>>> [', '.join(map(str, x)) for x in lis ]
['A, 1, 2', 'B, 3, 4']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
3

You can use nested list comprehensions with str.join:

>>> lst = [['A',1,2],['B',3,4]]
>>> [", ".join([str(y) for y in x]) for x in lst]
['A, 1, 2', 'B, 3, 4']
>>>
  • 1
    @alko Actually for large lists they are recommended. But for small lists, yes they can be dropped. – Ashwini Chaudhary Dec 03 '13 at 21:46
  • 1
    @alko - Yea. Here is a [reference](http://stackoverflow.com/a/9061024/2555451). –  Dec 03 '13 at 21:47
  • Just found topic myself. I wasn't aware of that 2-pass behaviour of join, thanks, @AshwiniChaudhary and @iCodez! – alko Dec 03 '13 at 21:50
0
li = [['A',1,2],['B',3,4],['A',0.111,0.123456]]

print    [', '.join(map(str,sli)) for sli in li]


def func(x):
    try:
        return str(int(str(x)))
    except:
        try:
            return '%.2f' % float(str(x))
        except:
            return str(x)

print map(lambda subli: ', '.join(map(func,subli)) , li)

return

['A, 1, 2', 'B, 3, 4', 'A, 0.111, 0.123456']
['A, 1, 2', 'B, 3, 4', 'A, 0.11, 0.12']
eyquem
  • 26,771
  • 7
  • 38
  • 46