-1

I have the following list of multiple tuples:

[('1', 'Mak'), ('2', 'Sam'), ('3', 'John')]

Type: <type 'list'>

Convert to:

['1,Mak\n', '2,Sam\n', '3,John\n']
MAK
  • 6,052
  • 24
  • 69
  • 116

5 Answers5

3

string.format with a list comprehension for Python 2.6+

['{}\n'.format(','.join(i)) for i in arr]

# ['1,Mak\n', '2,Sam\n', '3,John\n']

Or with Python 3.6+ using formatted string literals

[f"{','.join(i)}\n" for i in arr]
user3483203
  • 48,205
  • 9
  • 52
  • 84
3

You can use list comprehensions:

l = [('1', 'Mak'), ('2', 'Sam'), ('3', 'John')]
l = [x + ',' + y + '\n' for x, y in l]

so, now l becomes: ['1,Mak\n', '2,Sam\n', '3,John\n']

Rishabh Agrahari
  • 3,161
  • 2
  • 20
  • 21
1

Using a list comprehension.

l = [('1', 'Mak'), ('2', 'Sam'), ('3', 'John')]
print [",".join(i)+ "\n" for i in l]

or

Using a map with lambda.

Ex:

l = [('1', 'Mak'), ('2', 'Sam'), ('3', 'John')]
print map(lambda x: "{0}\n".format(",".join(x)), l)
Rakesh
  • 78,594
  • 17
  • 67
  • 103
1

How about this -

>>> l = [('1', 'Mak'), ('2', 'Sam'), ('3', 'John')]
>>> new_list = []
>>>
>>> for x in l:
...     new_list.append('%s%s' % (','.join(x), '\n'))
...
>>> new_list
['1,Mak\n', '2,Sam\n', '3,John\n']
>>>
Ejaz
  • 1,427
  • 3
  • 21
  • 49
1

you can use map and lambda to solve this problem .

#input
your_list = [('1', 'Mak'), ('2', 'Sam'), ('3', 'John')]
#result
result_list = list(map(lambda x:x[0]+x[1]+"\n",your_list))
Pawanvir singh
  • 373
  • 6
  • 17