user3615736
user3615736

Reputation: 31

Creating Sublists from a "List"

I have a list in a file, looks like this

c4a24534,2434b375,e750c718, .... 

I have split at "," and brought the below list.

x=
['c4a2', '4534'] 
['2434', 'b375']
['e750', 'c718']

I need to make two new lists out of this

i=
'c4a2'
'2434'
'e750'

and

 q=
'4534'
'b375'
'c718'

I have tried :

for x in line:
    x = [i.split() for i in x]

With this I am splitting the x .This gives me "i" part but how do i get the rest "q" ?

Upvotes: 1

Views: 5034

Answers (5)

alecxe
alecxe

Reputation: 473823

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)

Upvotes: 1

Kevin
Kevin

Reputation: 76194

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)

Upvotes: 0

Caramiriel
Caramiriel

Reputation: 7257

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.

Upvotes: 1

Damiii
Damiii

Reputation: 1373

#!/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 ?

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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)

Upvotes: 2

Related Questions