Python convertion of list of strings to list of tuples

自作多情 提交于 2019-12-13 03:33:59

问题


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)

回答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)



回答2:


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

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



回答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  


来源:https://stackoverflow.com/questions/23852462/python-convertion-of-list-of-strings-to-list-of-tuples

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!