Braian Braian - 9 months ago 45
Python Question

Joining two list in one array in python

I want to join the column of an excel file to other 4 columns of another excel file.

Here's the code:

Array1 = []
Arraytest1 = []
Arraytest2 = []
with open('file.txt', 'r') as f:
for line in f:
List1 = line.split('\t')[:4]
List2 = line.split('\t')[10]
print 'Array 1 :', Arraytest1

What I see in output is :

Array 1: [['A','B','C','D'],['E']]

Array 1: [['A','B','C','D'],'E',['X1','X1','X1','X1'], 'E', Y1]

But what I what is something like:

Array 1: ['A','B','C','D','E']

Array 1: ['X1','X1','X1','X1','Y1']

Array 1: ['X2','X2','X2','X2','Y2']

and so on..
I will appreciate your help

Answer Source
List1 = line.split('\t')[:4]

makes List1 a list already.


is putting that list into ArrayTest1, think ArrayTest1 = [[List1's contents]]

Then when you are extending it, you are flatting it once but there's a nested list, that's why you see the results.


List1 = line.split('\t')[:4]
List2 = line.split('\t')[10]
print 'Array 1   :', Arraytest1 

Or you can replace it with:

Arraytest1 += List1
Arraytest2 += List2

I'm sure you know but append adds the object to the list, extend adds each object in the iterable.


x = [1,2,3]
#x is now [1,2,3,[4,5]]


x = [1,2,3]
#x is now [1,2,3,4,5]
x.append(1) #throws error 

Split returns a list... but sometimes if you just want to split a string just cast it.

x = "hello"
x = x.split()
#x is now ['hello']

x = "hello"
x = list(x)
#x is now ['h', 'e', 'l', 'l', 'o']

Splitting sentences is what split usually do, Strings in Python are iterables so you can just cast them into list to split them up into each characters. I think that's what you want'

Edited: Based on your comments it's a for loop issue:

You are appending adding to the list as the for loop goes, but it seems like you want a new list everytime it loops. You aren't replacing the list with a clean one and you just appending to it everytime. try replacing:



Arraytest1 = List1[:]
Arraytest2 = List2[:]