Issues with printing in python a list of arrays - python

I'm new in the magic python world.
I have a problem: I save data from a file in a list of array (13 arrays of 130 element each) but when I try to print the values, only the same values with bracket are printed .
I defined the list and the array in this way:
List = []
v = np.ndarray(shape=(130,1),dtype=float)
After I fill my data structure from the file
f=open(filename, 'r').readlines()
k = 0
for i in range(0,13):
for j in range(0,130):
v[j] = float(f[k])
k += 1
List.append(v)
In the file I have for each line a float value and the total length is 13*130.
I don't even know if I feed correctly my data structure, what I only know is that the function that I would like to use expect a list of array instead of a matrix.
I tried different way for seeing if I saved in a correct way the data.
Do you have any suggestion?

You need to recreate v in every iteration of the outer loop:
for i in range(0,13):
v = np.ndarray(shape=(130,1),dtype=float)
for j in range(0,130):
v[j] = float(f[k])
k += 1
List.append(v)
Otherwise, you're just updating the same reference over and over again (list.append only appends the reference to the list, does not copy the list in question).

If your only problem is printing without the brackets, then I think what you want (see me comment on the post) is the following:
for row in list:
for item in row:
print item,
print "" # print a newline

You can try: for i in List: print(i)
If you do not want the brackets to be displayed : for i in a: print(' '.join(map(str,i)))
But if you want to have constant row widths, create a function that returns a string of the float of constant length :
def auxString(float, length):
s = str(float)
s+=(length-len(s))*' '
return s
string = lambda length: lambda float: auxString(float,length)
for i in List:
print(' '.join(map(string(5),i))) #if the maximum length of your string of float is 5

Related

Multiply or duplicate number in a list. Python

How can I duplicate myData. For example
myLen = [1,2,3,4,5,6]
duplicate the number by the length of the 'myLen' and also convert the string to number
myData = ['2']
output:
[2,2,2,2,2,2]
try:
list(map(int,myData*len(myLen)))
What you could do is selecting the index of the element you need in myLen and then apply it to my data:
i = 0
n = myLen[i]
myData = ['2']**n
Of course you could decide what position you need by changing the value of i but make sure it's not greater than the length of myLen otherwise you'll get an error.
Basically the syntax [x]**n creates a list of length n with element x in it.

How to find the averages of an argument which consists of nested arrays in python

This is the argument i would be passing to my logic.
var= '--a1=[[1,2,3],[]] --a2=4'
I need to find the average of these two arrays as mentioned below.
"1 4"
because [1,2,3] evaluates to 2, [] evaluates to 0 and the average of [2,0] is 1.
I have tried the code as given below,but its of no use.
var="--a1=[1,2,3] --a2=4.0"
args=var.split(' ')
args=[s[s.find('=') + 1:] for s in args]
print (args)
for elem in args:
for i in elem:
print (i)
Can someone please help me
Here is one way to do it:
(assuming you want the average, not the item located at the middle. If the middle is what you need, you should be able to adapt the following solution by yourself)
var="--a1=[1,2,3] --a2=4.0"
args=var.split(' ')
args=[s[s.find('=') + 1:] for s in args]
for elem in args:
# remove everything but numbers and commas (we don't care about nested arrays here)
# "[[[1,2,3],[]]" --> "1,2,3,"
stripped = "".join([ c for c in elem if c.isdigit() or c == ','])
# now, split by commas, and convert each number from string to int (ignore empty strings with `if d`)
# "1,2,3," --> [1,2,3]
numbers = [int(d) for d in stripped.split(",") if d]
# now, just compute the mean and print
avg = sum(numbers) / len(numbers)
print(avg)
I've utilized the inbuilt eval() function to solve your problem. I've tried my best to explain the code in the comments. Take a look at the code below:
def average(array): # returns the average of the values in an array
n = 0
if array == []:
return 0
else:
for i in array:
n += i
return n/len(array)
var= '--a1=[[1,2,3],[]] --a2=4'
start = var.find('[') # I used this method the find the first "[" in the string
end = len(var) - var[::-1].find(']') # I reversed the string to find the last "]" in the string
a1 = eval(var[start:end]) # converts the list in the form of string to a list
# for example "[1,2,3]" will be converted into [1,2,3] using the eval function
if var.count('[') == 1: # the code below requires a 2d array so this part converts the array to 2d if 1d is passed
a1 = [a1]
averages = [] # to store the averages of all of the lists
for array in a1:
averages.append(average(array)) # finding average for each array in the string
print(averages)

Removing third element from list until there are less than 3 numbers

I have a problem. I need to create a list . And in every iteration i need to remove the third element and print the list without the deleted element.
The thing is. I'm trying to do an algorithm of deleting the third element without remove function or other inbuilt list functions. In my code I covered the following possibilities. If my list has less than 3 elements I print a message saying the list is short. If my list has 3 elements in it I will assign the third element the value of the second element and so on. My problem is when my list has more than 3 elements.
v=[] # list of numbers the user inputs
two=[] #list with only 2 elements
vector=[] # list with third element deleted when len(v)>3
def create_array():
n=int(input('Digit total elements in dynamic array - '))
for i in range(0,n):
element=int(input('Digit element to array - '))
v.append(element)
return v
print(create_array())
def remove_third_element():
for j in range(0,len(v)):
if len(v)<3: # if number of elements in list < 3 there is no element to delete
print('There is no element do delete! ')
return 0
elif len(v)==3:
v[2]==v[1] and v[1]==v[0]
two=[v[0],v[1]]
return two
else:
v[0]==v[1] and v[1]==v[2]
print(remove_third_element())
elif len(v) > 3:
ret = [];
for i in range(len(v)):
if(i != 2) ret.append(v[i]);
return ret
should do the trick
By the way, with this method you can remove you elif len(v) == 3
Also your code :
elif len(v)==3:
v[2]==v[1] and v[1]==v[0]
two=[v[0],v[1]]
return two
won't work because '==' is used as condition in python so it will return a boolean and not assign value.
go for
v[2] = v[1]
v[1] = v[0]
instead
Here's a Pythonic way of making a new list without the original list's third element.
new_list = old_list[:2] + old_list[3:]
old_list[:2] is shorthand for "until the 2-th index" (so we'll get index 0 and 1) of the old_list.
old_list[3:] is shorthand for, "from 3rd index 'til the end" (so index 3, 4, etc.).
Both return lists; in python, if you add lists, concatenation actually happens.
As an example, if old_list = [1,2,3,4,5], then new_list[:2] will be [1,2] and new_list[3:] will be [4,5]. So combining that will be [1,2,4,5].
Notice that this statement: v[2]==v[1] and v[1]==v[0] won't assign values!
Operation == return boolean.
Lets say your v looks like this: v = [1, 1, 3].
Then v[2]==v[1] and v[1]==v[0] gives you result: False and True, and this gives you reulst False. You can check it if you print this print(v[2]==v[1] and v[1]==v[0]).
If you want to assign values, you can use a statement like this: v[2], v[1] = v[1], v[0].
def main():
big_list = [ x for x in range(20) ]
while len(big_list) > 3:
big_list = big_list[:2] + big_list[3:]
print(big_list)

list index out of range, python

I get an Error list index out of range when I'm trying to split a big list in to an array with arrays in it.
I have no idea why this is happening.
the end result of this code should be an array with arrays in it. So that i later can call for example val[5] and get 10 values.
I'm able to print val if the print statement is inside the for loop. And the code is working as it should. But if I move the print statement outside the for loop I get the Index out of range error.
import sys
import numpy as np
from numpy import array, random, dot
def vectorizeImages(filename):
file_object = open(filename)
lines = file_object.read().split()
#array to save all values that is digets.
strings = []
values = []
images = []
val = []
test=[]
#loop that checks if the position in the list contains a digit.
#If it does it will save the digit to the value-array.
for i in lines:
if i.isdigit():
strings.append(i)
#Converting all the strings to ints.
strings = list(map(int, strings))
#deviding every value in the array by 32
for i in strings:
a = i
values.append(a)
#splits large list into smaller lists and ads a 1
for i in range(len(values)):
a = []
for j in range(400):
a.append(values[i*400+j]) #ERROR:list index out of range
a.append(1)
val.append(a)
Your error is here: a.append(values[i*400+j]).
When i = 0, then you populate a and you end up with 400 elements. You do the full loop if your have at least 400 elements.
But at some point, you will ask for more elements than what you have in values, and then it fails because you loop and the biggest element you ask is len(values) * 400 - 1 which is obviously greater than your list size.
This is what I did to solve my problem (also improved my python skills)
def readImages(images):
lines = open(images).read().split()
images = []
values = [float(i)/32.0 for i in lines if i.isdigit()]
for i in range(len(values) / 400):
a = [values[i * 400 + j] for j in range(400)]
images.append(a)
return np.array(images)

Append result of iteration in python

I am pretty new to python, i am using python 3 and have some difficulties to append the result of the iteration to the array, following is my chunk of my code:
A = np.random.randn(len(meas),numx)
lengthA = np.linspace(0,len(A[0])-1,num=len(A[0]),dtype=int)
anorm = []
for j in range(0,len(lengthA)):
x_normed = A/A.max(axis=0)
anorm[:,j] = A[:,j]*x_normed[j]
Is it necessary to append the new result to empty anom ? somehow the code always tell me that the list of the indices must be integer and not tuple. Any help will be appreciated.
When assigning a value to an array at index n via the array[index] = value syntax, the argument within the square brackets must be an integer. In your situation, j is an integer but [:,j] attempts to reference multiple indices within the array.
for j in range(0,len(lengthA)):
x_normed = A/A.max(axis=0)
anorm[j] = A[:,j]*x_normed[j]
As an aside, if you want your for loop to run for as many iterations as there are elements within lengthA, then you can simply do:
for j in lengthA:
do stuff

Categories

Resources