Append does not update list values in Python - python

I would like to find the rolling mean of the last 10 elements in a list in Python, using something like:
...
mean_last_10 = stats.mean(data_list[i-10:i])
print("test mean", mean_last_10 )
array.append([id[i],a[i], mean_last_10])
The printed values look correct but the array shows that values for mean_last_10 is kept the same. Why is this the case? Should I use deepcopy?

Outside your for loop create a list
mean_last_10 = []
mean_last_10.append(stats.mean(data_list[i-10:i]))
array.append([id[i],a[i], mean_last_10[i]])

Related

How to merge several Python lists together using for loop

I am writing a script in order to calculate all the euclidean distances between a X value and a lot of other values in a dictonary, obtaining a float that, then, I convert in a list. The problem is I don't obtain a list with all the outcomes but many lists with only one element inside, my outcome.
My script for the moment is:
single_mineral = {}
for k in new_dict.keys():
single_mineral = new_dict[k]
Zeff = single_mineral["Zeff_norm"]
rhoe = single_mineral["Rhoe_norm"]
eucl_Zeff= (calculated_Zeff_norm, Zeff)
eucl_rhoe= (calculated_rhoe_norm, rhoe)
dst= [(distance.euclidean(eucl_Zeff, eucl_rhoe))]
print(dst)
I obtain something like that:
[0.29205348037179407]
[0.23436642937625374]
[0.3835446564476642]
[0.11616594912309205]
[0.21792958584034935]
and they are not linked somehow (so I can't use intertools.chain).
I want to create a single list with all these lists (the final goal is the ascending order...for this reason I need only one list).
I guess the solution is a for loop but I have no idea how to do it. I don't understand where it needs to run and how can I add my outcomes, which are always called "dst"?
Please, help me! Thank you very much in advance!
if you want to do get all in one list then you need
# before loop
dst = []
# loop
for k in new_dict.keys():
# ... code ...
#dst.append( [distance.euclidean(eucl_Zeff, eucl_rhoe)] )
dst.append( distance.euclidean(eucl_Zeff, eucl_rhoe) )
# after loop
print(dst)

Extracting data out of Complex JSON

This is the JSON data I am using
In this dataset, I want to extract the value of "yaw" and store it into in camera_loc. My first attempt for the code was as follows:
with open(
"/home/siddhant/catkin_ws/src/view-adaptation/multi_sensors.json"
) as sensors:
multi_sensors = json.load(sensors)
camera_loc = [
multi_sensors["sensors"][0]["yaw"],
multi_sensors["sensors"][1]["yaw"],
multi_sensors["sensors"][2]["yaw"],
multi_sensors["sensors"][3]["yaw"],
multi_sensors["sensors"][4]["yaw"],
multi_sensors["sensors"][5]["yaw"],
]
This gives me the expected result.
But I want to generalize the same for any number of entries in the 'sensors' array.
I tried executing a 'for' loop and extracting the values for the same as follows:
for i in multi_sensors["sensors"]:
camera_loc = []
camera_loc.append(i["yaw"])
However, this method only gives a single value in the camera_loc list which is the last 'yaw' value from the JSON file. I am looking for a better approach or even any modifications to the way I execute the loop so that I can extract all the values of 'yaw' from the JSON file - in this example there are 6 entries but I want to generalize it for 'n' entries that may be created in other cases.
Thank you!
That's because you're defining your camera_loc array inside the loop, meaning every iteration resets it to []. This code should work if you remove the array definition from the loop:
camera_loc = []
for i in multi_sensors["sensors"]:
camera_loc.append(i["yaw"])
This is also a perfect use case for a List Comprehension:
camera_loc = [i["yaw"] for i in multi_sensors["sensors"]]
Both answers results in the same array though, so you may choose whichever you like most.

Searching index of a range of values in an array using python

I am using the following code to find the indices
result1=np.where(np.logical_and(R[i,:]>= 30, R[i,:]<= 30.3))
The output is
result1 = (array([284, 285]),)
When I run len(result1) I get a value of one.
Why is the length one when there are 2 elements.
The two numbers are indexes. I need to use the indexes but cannot because len(result1) is one.
I tried changing it to list but that did not help.
Please help me with this.
result1 is a tuple containing a single array, and thus has a length of 1; it is the array that has 2 elements.
You can use like len(result1[0]) or if you can remember later use like this; result1 = ([284,285],'') -> len(result1).

Python creating a list with variable size which contains floating points

I want to be able to create a 2d list with a variable size.
test = [[]]
The problem is the data I want to put inside of it is a floating point. This makes it incompatible with the append function
TempData[0] = 1
TempData[1] = 2.32
TempData[2] = 3.65
test.append(float(TempData))
Is There any way around this? I don't really want to declare a huge list because sometimes the 2D list size may be very big or very small.
It looks like your issue is due to passing an object, TempData to a list and then changing the contents of that object. A reference to TempData is stored in the list, not the values contained in that list. When you alter TempData, it alters every element in the list. Instead, try this:
test = []
test.append([1, 2.32, 3.65])
test.append([2.312, 1.231, 1.111])
The python array module is made specifically for the purpose of holding numeric values. Here is an example using a list and an array.array:
import array
mylist = []
mylist.append(array.array('f', [1.43, 1.54, 1.24]))

Can I condense these values with a loop?

I have a set of values that get modified like so:
iskDropped = irrelevant1
iskDestroyed = irrelevant2
iskTotal = irrelevant3
iskDropped = condense_value(int(iskDropped[:-7].replace(',','')))
iskDestroyed = condense_value(int(iskDestroyed[:-7].replace(',','')))
iskTotal = condense_value(int(iskTotal[:-7].replace(',','')))
As you can see, all three lines go through the same changes. (condensed, shortened, and commas removed) before overwriting their original value.
I want to condense those three lines if possible because it feels inefficient.
I was trying something like this:
for value in [iskDropped,iskDestroyed,iskTotal]:
value = condense_value(int(value[:-7].replace(',','')))
which if you changed into a print statement successfully does print the correct values but it does not work in the regard of overwriting / updating the values (iskDropped,iskDestroyed, and iskTotal) that I need to call later in the program.
Is it possible to condense these lines in Python? If so can someone point me in the right direction?
You can do it like this:
iskDropped, iskDestroyed, iskTotal = [condense_value(int(value[:-7].replace(',',''))) for value in [iskDropped, iskDestroyed, iskTotal]]
This works by looping through the list of your 3 variables, performing the condense_value function on each and creates a list of the results, then finally unpacks the list back into the original values.

Categories

Resources