0

How to convert following list

['abc,cde,eg,ba', 'abc,cde,ba']

in to list of tuples?

[('abc','cde','eg','ba'), ('abc','cde','ba')]

What I have tried

output = []

for item in my_list:
    a = "','".join((item.split(',')))
    output.append(a)
Nilani Algiriyage
  • 32,876
  • 32
  • 87
  • 121

3 Answers3

2

In your loop, you are splitting the string (which will give you a list), but then you are joining it back with a ,, which is returning to you the same string:

 >>> 'a,b'.split(',')
 ['a', 'b']
 >>> ','.join('a,b'.split(','))
'a,b'

You can convert a list to a tuple by passing it to the the built-in tuple() method.

Combining the above with a list comprehension (which is an expression that evaluates to a list), gives you what you need:

>>> [tuple(i.split(',')) for i in ['abc,cde,eg,ba', 'abc,cde,ba']]
[('abc', 'cde', 'eg', 'ba'), ('abc', 'cde', 'ba')]

The longhand way of writing that is:

result = []
for i in ['abc,cde,eg,ba', 'abc,cde,ba']:
    result.append(tuple(i.split(',')))
print(result)
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
2
t=['abc,cde,eg,ba', 'abc,cde,ba']

for i in t:
    print tuple(i.split(','))
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
1

you can split the 2 elements. Here is my code

['abc,cde,eg,ba', 'abc,cde,ba']
a='abc,cde,eg,ba'
b='abc,cde,ba'
c=[]
c.append(tuple(a.split(',')))
c.append(tuple(b.split(',')))
print c  
user3670684
  • 1,135
  • 9
  • 8