Skip to content Skip to sidebar Skip to footer

Python Convertion Of List Of Strings To List Of Tuples

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_l

Solution 1:

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)

Solution 2:

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

for i in t:
    print tuple(i.split(','))

Solution 3:

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  

Post a Comment for "Python Convertion Of List Of Strings To List Of Tuples"