Convert list of string to List of tuples

2.6k views Asked by At

I have a list of string as below

['40799\t1890\t11-16-15\n', '40800\t1890\t11-17-15\n', '40801\t1890\t11-18-15\n', '40802\t1890\t11-19-15\n']

Want to convert as below

 [('40799',1890,'11-16-15'), ('40800',1890,'11-17-15'), ('40801',1890,'11-18-15'), ('40802',1890,'11-19-15')]

Tab is the separator for each column. I am able to convert using some loop. But would like to know if it is possible to convert the list using a single command as the list may have lot of items

3

There are 3 answers

2
jamylak On BEST ANSWER
>>> data = ['40799\t1890\t11-16-15\n', '40800\t1890\t11-17-15\n', '40801\t1890\t11-18-15\n', '40802\t1890\t11-19-15\n']
>>> [(x, int(y), z) for x, y, z in (line.split() for line in data)]
[('40799', 1890, '11-16-15'), ('40800', 1890, '11-17-15'), ('40801', 1890, '11-18-15'), ('40802', 1890, '11-19-15')]
3
Mahesh Karia On
lst = ['40799\t1890\t11-16-15\n', '40800\t1890\t11-17-15\n', '40801\t1890\t11-18-15\n', '40802\t1890\t11-19-15\n']

print [tuple(s.split()) for s in lst]

output:

[('40799', '1890', '11-16-15'), ('40800', '1890', '11-17-15'), ('40801', '1890', '11-18-15'), ('40802', '1890', '11-19-15')]
3
Pankaj Singhal On
>>> data = ['40799\t1890\t11-16-15\n', '40800\t1890\t11-17-15\n', '40801\t1890\t11-18-15\n', '40802\t1890\t11-19-15\n']
>>> [tuple(line.split()) for line in data]
[('40799', '1890', '11-16-15'), ('40800', '1890', '11-17-15'), ('40801', '1890', '11-18-15'), ('40802', '1890', '11-19-15')]