-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,824
  • 25
  • 74
  • 131

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
  • 50,081
  • 9
  • 65
  • 94
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,447
  • 2
  • 21
  • 22
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
  • 81,458
  • 17
  • 76
  • 113
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,504
  • 3
  • 25
  • 51
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