Python 2d array iteration - python

I have two lists, one with a parameter name and one with a pin name, and I am trying to combine the two lists into a 2d matrix but I cannot get the syntax right.
For example:
list1 = [parm1,parm2,parm3]
list2 = [end1,end2,end3]
and I want the matrix to be:
matrix1= [[parm1+ end1,parm1+end2, parm1+end3]
[parm2+ end1,parm2+end2, parm2+end3]
[parm3+ end1,parm3+end2, parm3+end3]
right now my code is
for i in range(len(parm_name)):
for j in range(len(end_name)):
pin_name[i][j] = parm_name[i] + end_name[j]
and it's not working.

Instead of reassigning elements of a preinitialized list, simply create a new one:
list1 = [parm1,parm2,parm3]
list2 = [end1,end2,end3]
matrix1 = [[p+e for e in list2] for p in list1]
That last line can be expanded into the following equivalent code:
matrix1 = []
for p in list1:
result = []
for e in list2:
result.append(p+e)
matrix1.append(result)

You can create matrix1 with the following:
matrix1 = [[p_name + e_name for e_name in list2] for p_name in list1]
You don't give much code so it's difficult to say why yours isn't working. I suspect that you don't initialize your matrix appropriately. But you don't need to initialize then assign, you can do it all in one step with list comprehension

Related

Function squaring 2-d array python

I have a function that takes in any 2-d array and return a 2-d array (the same format as the array being implemented) but the values are squared.
i.e [[1,2],[3,4]] -----> [[1,4],[9,16]]
my code so far:
m0 = [[1,2],[3,4]]
empty_list = []
for x in m0:
for i in x:
empyt_list.append(x**2)
This gives me a 1-d array but how would i return a 2-d array as the imputed value?
You can make a recursive function to handle any depth of nested lists:
def SquareList(L):
if type(L) is list:
return [SquareList(x) for x in L]
else:
return L**2
Example:
> print(SquareList([1,[3],[2,[3]],4]))
[1, [9], [4, [9]], 16]
Working with an outer list
The point is that you will need an extra list outside to store the columns. So we can introduce temporary lists we build up and add as rows:
m0 = [[1,2],[3,4]]
result = []
for sublist in m0:
row = []
for item in sublist:
row.append(item**2)
result.append(row)
Notice that we here iterate over the items of the sublist.
Using list comprehension
We can however write this more elegantly with list comprehension
result = [[x*x for x in sublist] for sublist in m0]
Note: if you have to square a number x, it is usually more efficient to use x * x, then to write x ** 2.
Using numpy (for rectangular lists)
In case the list is rectangular (all sublists have the same length), we can use numpy instead:
from numpy import array
a0 = array(m0)
result = a0 ** 2
You can just do this by a list comprehension:
empty_list = [[m0[i][j]**2 for j in range(len(m0[i]))] for i in range(len(m0))]
Or like your Codestyle:
empty_list = m0
for i in range(len(m0)):
for j in range(len(m0[i])):
empty_list[i][j] = m0[i][j] ** 2
Your problem is that you never created a 2D-list and you just append the values on the created 1D-list.

How to merge n lists together item by item for each list

I want to make one large list for entering into a database with values from 4 different lists. I want it to be like
[[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]], etc.....]
Another issue is that currently the data is received like this:
[ [ [list1[0], list1[1], [list1[3]]], [[list2[0]]], etc.....]
I've tried looping through each list using indexs and adding them to a new list based on those but it hasn't worked, I'm pretty sure it didn't work because some of the lists are different lengths (they're not meant to be but it's automated data so sometimes there's a mistake).
Anyone know what's the best way to go about this? Thanks.
First list can be constructed using zip function as follows (for 4 lists):
list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = [9,10,11,12]
list4 = [13,14,15,16]
res = list(zip(list1,list2,list3,list4))
For arbitrtary number of lists stored in another list u can use *-notation to unpack outer list:
lists = [...]
res = list(zip(*lists))
To construct list of lists for zipping from you data in second issue use flatten concept to it and then zip:
def flatten(l):
res = []
for el in l:
if(isinstance(el, list)):
res += flatten(el)
else:
res.append(el)
return res
auto_data = [...]
res = list(zip(*[flatten(el) for el in auto_data]))
Some clarification at the end:
zip function construct results of the smallest length between all inputs, then you need to extend data in list comprehension in last code string to be one length to not lose some info.
So if I understand correctly, this is your input:
l = [[1.1,1.2,1.3,1.4],[2.1,2.2,2.3,2.4],[3.1,3.2,3.3,3.4],[4.1,4.2,4.3,4.4]]
and you would like to have this output
[[1.1,2.1,3.1,4.1],...]
If so, this could be done by using zip
zip(*l)
Make a for loop which only gives you the counter variable. Use that variable to index the lists. Make a temporary list , fill it up with the values from the other lists. Add that list to the final one. With this you will et the desired structure.
nestedlist = []
for counter in range(0,x):
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
If all the 4 lists are the same length you can use this code to make it even nicer.
nestedlist = []
for counter in range(0,len(firstlist)): #changed line
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
This comprehension should work, with a little help from zip:
mylist = [i for i in zip(list1, list2, list3, list4)]
But this assumes all the list are of the same length. If that's not the case (or you're not sure of that), you can "pad" them first, to be of same length.
def padlist(some_list, desired_length, pad_with):
while len(some_list) < desired_length:
some_list.append(pad_with)
return some_list
list_of_lists = [list1, list2, list3, list4]
maxlength = len(max(list_of_lists, key=len))
list_of_lists = [padlist(l, maxlength, 0) for l in list_of_lists]
And now do the above comprehension statement, works well in my testing of it
mylist = [i for i in zip(*list_of_lists)]
If the flatten concept doesn't work, try this out:
import numpy as np
myArray = np.array([[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]]])
np.hstack(myArray)
Also that one should work:
np.concatenate(myArray, axis=1)
Just for those who will search for the solution of this problem when lists are of the same length:
def flatten(lists):
results = []
for numbers in lists:
for output in numbers:
results.append(output)
return results
print(flatten(n))

Referencing value and values after it

Let's say I have a list:
list1 = [1,2,3,4,5,6,7,8,9,10]
I want a loop that will, for every value, check if a concatenated version of it and any other beyond it are the same as an existing value in another list. Make sense? No? Here's what I want to come out.
The lists
list1 = ['3','ex','fish nets','orange','banana','exampl','apple']
list2 = ['e','x','blah','exam','p','l','blahblah']
Finally, we take these lists and let's say I want every time a value and any adjacent number of values after it are equivalent to a value in list1 for them to concatenate. (i.e. values e and x concatenate to be ex which exists in list1.) So, it modifies list2 to be:
list2 = ['ex','blah','exam','p','l','blahblah']
The same would be for three or four or however many values are in the list. The loop would reexamine the rest of possible combinations (only left -> right) and do the same. exam, p, and l concatenate to the value in list1 exampl. list2 then becomes:
list2 = ['ex','blah','exampl','blahblah']
The wording on this is pretty poor but I hope the examples were in-depth enough to give a representation of what I need.
list1 = ['3','ex','fish nets','orange','banana','exampl','apple']
list2 = ['e','x','blah','exam','p','l','blahblah']
a=list2
j=['e','x','blah','exam','p','l','blahblah']
t=[]
for y in range(0, len(j)):
for i in range(1,len(j)-y):
r=''
t=j[y:y+i+1] #Create a list of adjacent elements.
for x in t:
r+=str(x) #make it string and check if it fits.
if r in list1:
list2[y]=r
for e in range(y+1,y+i+1):
list2[e]=0 # to avoid a mess with indexes.
while 0 in list2:
list2.remove(0)
print list2
I know it's very clumpsy, but it seems to work.

python if statement to check a column for a value and do a command

for z in range(0,countD.shape[0]):
if countD[z,0] in background_low1[:,0]:
background_lowCountD.append(countD[z,:])
else:
background_goodCountD.append(countD[z,:])
I'm using the above code and getting a "list indices must be integers, not tuple" error message. I have two uneven arrays (CountD and background_low1), If a value is present in column 0 of both arrays at any row level I want to move that row to a new array, if its only present in 1 I want that row moved to a second new array.
You are getting this error message because lists are unidimensional (in theory). But since a list can contain another list, you can create a multidimensional list. Now accessing an element of a list is done using an index (which must be an integer) between brackets. When dealing with multidimensional lists, just use multiple brackets one after the other :
>>> a = ['a','b','c']
>>> b = [1,2,a]
>>> print b[2]
>>> ['a','b','c']
>>> print b[2][0]
>>> 'a'
So, to answer your question, try something like this :
list1 = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12]]
list2 = [[1,4,5,6],
[7,6,7,8],
[9,1,2,3]]
newList = []
otherList = []
#you need to make sure both lists are the same size
if len(list1) == len(list2):
for i in range(len(list1)):
if list1[i][0] == list2[i][0]:
newList.append(list1[i])
else:
otherList.append(list1[i])
#the lists should now look like this
>>> print newList
>>> [[1,2,3,4],[9,10,11,12]]
>>> print otherList
>>> [[5,6,7,8]]

Variable changing itself?

So I am working on a project, and this bit of code is acting funny. I wanted a function that would take a list (list1) , make a copy (list2) of that list and trim certain objects from the copy only. I only wrote code to subtract items from the copy, be the original keeps getting changed as well.(?) I just don't understand how the original list (list1) is being subtracted from. Code underneath, thank you in advance for your help..
def copyandtrim(w, x, y, z):
list1 = [w, x, y ,z]
list2 = []
list2 = (list1)
testlen = (len(list2))
for y in range(testlen - 1):
if (list2[y])[2] == 0:
list2.remove(list2[y])
else:
pass
In order to make a copy of list1 in list2 you should do this:
list2 = list1[:]
But be careful, using list2.remove(list2[y]) changes list2, so further indexes are shifted as well. I would suggest this alternative to your loop:
list2 = [x for x in list1 if x[2] != 0]
list2 = list1 doesn't actually do a deep copy of the list object. It simply points list2 to refer to the same list object. To get a copy, the easiest way is to use:
list2 = list1[:]
To copy list in python you should use slice operation:
list2 = list1[:]

Categories