I have a list in a file, looks like this
c4a24534,2434b375,e750c718, ....
I have split at \",\" and brought the below list.
x
Assuming this is a contents of input.txt
file:
c4a24534,2434b375,e750c718
Use zip() for splitting into two lists:
with open('input.txt') as f:
i, q = zip(*((x[:4], x[4:]) for line in f for x in line.split(',')))
print i
print q
Prints:
('c4a2', '2434', 'e750')
('4534', 'b375', 'c718')
These are tuples, if you need to make lists from them, call list()
on each:
print list(i)
print list(q)
You can use zip
to separate the list into two collections.
x=[
['c4a2', '4534'],
['2434', 'b375'],
['e750', 'c718']
]
i,q = zip(*x)
print i
print q
Result:
('c4a2', '2434', 'e750')
('4534', 'b375', 'c718')
These are tuples, though. If you really want lists, you would need to convert them.
i,q = map(list, zip(*x))
#or:
i,q = [list(tup) for tup in zip(*x)]
#or:
i,q = zip(*x)
i, q = list(i), list(q)
#!/usr/bin/python
import ast
file = open("file.txt","r")
i = list()
q = list()
for line in file:
testarray = ast.literal_eval(line)
q.append(testarray.pop())
i.append(testarray.pop())
print(i)
print(q)
something like that ?
If you have read a list of lists, use zip()
to turn columns into rows:
file_result = [
['19df', 'b35d']
['fafa', 'bbaf']
['dce9', 'cf47']
]
a, b = zip(*file_result)
Taking for granted that you've already parsed the file:
x = [['c4a2', '4534'], ['2434', 'b375'], ['e750', 'c718']]
i = [a[0] for a in x] # ['c4a2', '2434', 'e750']
q = [a[1] for a in x] # ['4534', 'b375', 'c718']
This takes the first and second element of each sub-list, and puts it into a new variable.