change value 2d array in Python - python

I have an array with 20 values, but value 16 is incorrent and must be replaced with the correct value. How can I do that?
texture[16] = 'sky13.jpg'
That code does not work for some reason. The error is "'tuple' object does not support item assignment"

You're working with a tuple instead of a list. Convert it to a list first
texture = list(texture)
texture[16] = 'sky13.jpg

check what texture is
type(texture)
if it is tuple then convert it to list
textute = list(texture)
in python simple way to talk tuple object is immutable list object
more about differences is here What's the difference between lists and tuples?

Tuples in Python are **inmutable**, which means that you can't change the value once you assign it!
You need to convert the tuple to a list:
listOfTextures = list(texture)
And then you will be able to change the values you want to.

Related

List is immutable? Cannot convert list of strings ---> list of floats

I have a list of values, titled 'list', with values 23.4158, 25.3817, 26.4629, 26.8004, 26.6582, 27.7, 27.8476, 28.025. Each value is a string, not a float. Thus, I would like to convert this to a list of floats.
When I create a for loop to reassign the strings as floats, using the float() function, within the loops it shows me that the str has been successfully converted to a float. But when I check the type outside the loop, it shows me they are still strings.
for i in list:
i = float(i)
print(i,"=", type(i))
print(type(list[0]))
HOWEVER. When I create an empty list (new_list), and append the converted floats into said list, it shows exactly what I want. In other words, the str--->float conversion is successful. Code as such:
new_list = list()
for i in list:
i = float(i)
print(i,"=", type(i))
new_list.append(i)
print(type(new_list[0]))
Why is it that the reassignment does not 'stick' unless the values are appended to new_list? Lists are mutable, so the old list should be able to be modified. Am i missing something?
The reassignment does not "stick" because you are not converting the item inside the list, you are converting i, which is another value inside the loop, completely detached from the list object. You are just converting a new variable i to float, you are not converting the item from within the list. The variable i is a new variable and python just copied the value from the item inside the new variable i. You are not converting the item from the list, you are converting a new variable i that has the same value as the item that the loop is currently at.
If you want to convert the item from withing the list using a for loop, you must target the item itself using its index:
values = [
"23.4158", "25.3817", "26.4629", "26.8004", "26.6582", "27.7", "27.8476", "28.025"
]
for i in range(len(values)):
values[i] = float(values[i])
print(values)
print(type(values[0]))
The reason why it works when appending to a list is because you are appending the newly converted i, which indeed, is a float.
I suggest reading the following:
What does Python treat as reference types?
https://www.geeksforgeeks.org/pass-by-reference-vs-value-in-python/
https://www.tutorialsteacher.com/csharp/csharp-value-type-and-reference-type

How to break a list into couple lists

Assume that I have a list with size=(8,64,1,60,60) and want to break it into (4,2,64,1,60,60) and then sum them up along axis 1. I tried the code below but it raised with error :
'list' object has no attribute 'reshape'.
Please note that I want to keep the predictions as a list and do not want to change it to array.
predictions=list(np.random.randint(5,size=(8,64,1,60,60)))
predictions_sum = predictions.reshape(4,2, *predictions.shape[1:]).sum(axis=1)
You are confusing Python's built-in list type with numpy's array. Try this:
predictions=np.array(np.random.randint(5,size=(8,64,1,60,60)))
predictions_sum = predictions.reshape(4,2, *predictions.shape[1:]).sum(axis=1)

Datastructure choice issue

I'm new to Python. I need a data structure to contain a tuple of two elements: date and file path. I need to be able to change their values from time to time, hence I'm not sure a tuple is a good idea as it is immutable. Every time I need to change it I must create a new tuple and reference it, instead of really changing its values; so, we may have a memory issue here: a lot of tuples allocated.
On the other hand, I thought of a list , but a list isn't in fixed size, so the user may potentially enter more than 2 elements, which is not ideal.
Lastly, I would also want to reference each element in a reasonable name; that is, instead of list[0] (which maps to the date) and list[1] (which maps to the file path), I would prefer a readable solution, such as associative arrays in PHP:
tuple = array()
tuple['Date'] = "12.6.15"
tuple['FilePath] = "C:\somewhere\only\we\know"
What is the Pythonic way to handle such situation?
Sounds like you're describing a dictionary (dict)
# Creating a dict
>>> d = {'Date': "12.6.15", 'FilePath': "C:\somewhere\only\we\know"}
# Accessing a value based on a key
>>> d['Date']
'12.6.15'
# Changing the value associated with that key
>>> d['Date'] = '12.15.15'
# Displaying the representation of the updated dict
>>> d
{'FilePath': 'C:\\somewhere\\only\\we\\know', 'Date': '12.15.15'}
Why not use a dictionary. Dictionaries allow you to map a 'Key' to a 'Value'.
For example, you can define a dictionary like this:
dict = { 'Date' : "12.6.15", 'Filepath' : "C:\somewhere\only\we\know"}
and you can easily change it like this:
dict['Date'] = 'newDate'

Converting Str to Integer

I get the following error: TypeError: list indices must be integers, not str on this line of code:
a= doc['coordinates']['coordinates']
This is reading records from a db, I would like to know how to convert this into an integer from str?
Thanks
EDIT:
doc['coordinates']['coordinates'] returns coordinate information from a mongoDB, where these are the fields. It returns the relevant information for the first ten times the program runs, then I get this error.
Look at what is happening here:
a= doc['coordinates']['coordinates']
First doc['coordinates'] is evaluated. This returns a list of coordinates, lets say [32.9,23.11].
Now you're trying to look up something in this list with the index 'coordinates'.
a = [32.9,32.11]['coordinates']
This is your list: [32.9,32.11]
Lists only have numerical indices, in this case: 0 and 1.
If you're trying to assign a list of coordinates to a variable, you could just do a = doc['coordinates'] or if you want an individual coordinate, doc['coordinates'][0]

How to declare and add items to an array in Python?

I'm trying to add items to an array in python.
I run
array = {}
Then, I try to add something to this array by doing:
array.append(valueToBeInserted)
There doesn't seem to be a .append method for this. How do I add items to an array?
{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].
To initialize an empty list do this:
my_list = []
or
my_list = list()
To add elements to the list, use append
my_list.append(12)
To extend the list to include the elements from another list use extend
my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]
To remove an element from a list use remove
my_list.remove(2)
Dictionaries represent a collection of key/value pairs also known as an associative array or a map.
To initialize an empty dictionary use {} or dict()
Dictionaries have keys and values
my_dict = {'key':'value', 'another_key' : 0}
To extend a dictionary with the contents of another dictionary you may use the update method
my_dict.update({'third_key' : 1})
To remove a value from a dictionary
del my_dict['key']
If you do it this way:
array = {}
you are making a dictionary, not an array.
If you need an array (which is called a list in python ) you declare it like this:
array = []
Then you can add items like this:
array.append('a')
Arrays (called list in python) use the [] notation. {} is for dict (also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.
If you actually want an array (list), use:
array = []
array.append(valueToBeInserted)
Just for sake of completion, you can also do this:
array = []
array += [valueToBeInserted]
If it's a list of strings, this will also work:
array += 'string'
In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:
Java:
int[] myIntArray = {1,2,3};
String[] myStringArray = {"a","b","c"};
However, in Python, curly braces are used to define dictionaries, which needs a key:value assignment as {'a':1, 'b':2}
To actually define an array (which is actually called list in python) you can do:
Python:
mylist = [1,2,3]
or other examples like:
mylist = list()
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
>>> [1,2,3]
You can also do:
array = numpy.append(array, value)
Note that the numpy.append() method returns a new object, so if you want to modify your initial array, you have to write: array = ...
Isn't it a good idea to learn how to create an array in the most performant way?
It's really simple to create and insert an values into an array:
my_array = ["B","C","D","E","F"]
But, now we have two ways to insert one more value into this array:
Slow mode:
my_array.insert(0,"A") - moves all values ​​to the right when entering an "A" in the zero position:
"A" --> "B","C","D","E","F"
Fast mode:
my_array.append("A")
Adds the value "A" to the last position of the array, without touching the other positions:
"B","C","D","E","F", "A"
If you need to display the sorted data, do so later when necessary. Use the way that is most useful to you, but it is interesting to understand the performance of each method.
I believe you are all wrong. you need to do:
array = array[] in order to define it, and then:
array.append ["hello"] to add to it.

Categories