How to fix list assignment index out of range error even after appending the array - python-3.x

I'm trying to get user's input through the entry widget into an array, keep note that the user's input is a number. How can I get the users input as an integer.
I tried changing the entry values to int with int(g.get())
but it gives me this line:
...
ValueError: invalid literal for int() with base 10: ''
...
So I tried putting it as a string first with int(str(g.get())
But that gave me the same error line.
Tried it outside the loop to get the values in the array, inside the loop, both, nothing worked.
I'm also not sure if my input into an array algorithm works, I'm thinking I might need to put the widget inside the array(?).
x = 6
ind = np.arange(N)
arr = []
G = tk.Entry(self, textvariable="")
G.pack
while x >= 0:
arr[x] = int(str(G.get()))
arr.append(x)
x = x - 1
I expect to have an array of numbers that the user inputted into the entry widget, for example, arr = [6,4,6,3,7]

Related

List Index Error - Combining list elements via index

'Original String = 1234 A 56 78 90 B'
def func_1(one_dict):
global ends
ends = []
for x in original_string:
if x in one_dict:
ends.append(one_dict[x])
return ends
The above returns:
['B', 'A']
My next function is supposed to then combine them into 1 string and get value from dictionary. I've tried this with/without the str in mult_ends with the same result.
def func_2(two_dict):
global mult_ends
mult_ends = str(ends[0] + ends[1])
for key in mult_ends:
if key in two_dict:
return two_dict[key]
The results confuse me since I use pretty identical processes in other functions with no issue.
IndexError: list index out of range
Why would the list index be out of range when there is clearly a 0 and 1? I've also added global ends to func_2 and I still received the same error.
*** RESTRUCTURED FUNCTIONS INTO 1 ***
def func_1(one_dict):
global ends
ends = []
for x in original_string:
if x in one_dict:
ends.append(one_dict[x])
mult_ends = ends[0] + ends[1]
for key in two_dict:
if key in mult_ends:
return ends_final_dict[key]
return None
Now, it actually does what I want it to do and returns the correct dictionary key in the event log:
A B
However, it does not return when I try to insert it back into my GUI for the user and it still throws the IndexError: list index out of range.

Is there a way to test if two separate values, in two separate arrays, and check if they are equal or not?

Im trying to see if a value in one array is equal to that in another array, the values are integer values.
Ive tried turning them into string and integers from the array but get the error that they cannot be converted implicitly.
winningnumber = []
usernumber = []
print(winningnumber)
print(usernumber)
if(winningnumber == usernumber):
print("Exact number")
I would then get an output like so
[1]
['1']
In order to do this, what you want to do is access the first item of each array, and compare that value.
There are a lot of ways to do this, but here is a little driver program to show you one way.
# Defining a function to see if they match
def is_winning(arr1, arr2):
# Grabbing the first element in each array
# denoted by the [0], for the "0th" element
arr1_first_ele = arr1[0]
arr2_first_ele = arr2[0]
# If the first element in the first array matches the first element in the second
if arr1_first_ele == arr2_first_ele:
# Print out they match
print("They match")
# Otherwise
else:
# Print out that they dont
print("They don't match")
def main():
# Example arrays
test_array_one = [1,3,4]
test_array_two = [5,4,3]
# This should print out "They don't match"
is_winning(test_array_one, test_array_two)
# Example arrays
test_array_three = [6,7,8]
test_array_four = [6,5,4]
# This should print out "They match"
is_winning(test_array_three, test_array_four)
main()
This evaluates to:
They don't match
They match

Length of list within list (jagged list) becomes zero after leaving loop

All -
For a Selenium webscraper using Python 3.x - I am trying to get a printout that depends upon the length of each 1d index in a jagged list, in this case only 2d. The list is named masterViewsList, and the lists it contains are versions of a list named viewsList. Below see how my list masterViewsList of viewsList's is constructed:
from selenium import webdriver
import os
masterLinkArray = []
masterViewsList = []
# a bunch of code here that I cut out for simplicity's sake
for y in range(0, len(masterLinkArray)):
browser = webdriver.Chrome(chromePath)
viewsList = []
browser.get(masterLinkArray[y])
productViews = browser.find_elements_by_xpath("// *[ # id = 'lightSlider'] / li / img")
counter = - 1
for a in productViews:
counter = counter + 1
viewsList.append(a.get_attribute('src'))
print(viewsList[counter])
print(len(viewsList))
masterViewsList.append(viewsList)
if y == 10:
print(masterViewsList[y])
print(len(masterViewsList[y]))
del viewsList[:]
print(len(masterLinkArray))
print(len(masterViewsList))
print(len(masterViewsList[0]))
print(len(masterViewsList[1]))
print(len(masterViewsList[10]))
The printout is this:
["https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM2_Front%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Side%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Interior%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Other%20view.jpg?wid=140&hei=140","https://us.testcompany.com/images/is/image/lv/1/PP_VP_L/544_PM1_Other%20view2.jpg?wid=140&hei=140"]
5
79
79
0
0
0
As you can see, neither the masterLinkArray, nor the masterViewsList are empty - they're 79 long. Also, print(masterViewsList[y]) prints out an actual non-empty list, one with a recognized length of 5. Oddly, once I leave the for y loop, len(masterViewsList[*any integer*]) prints out to "0". These similar questions:
Find the dimensions of a multidimensional Python array,
Find length of 2D array Python,
both indicate that len(array[*integer*]) is the proper way to get the length of a list within a list, but in my case this appears not to be working consistently.
The masterViewlist is empty a the point where you call the len method on it. That's why all the results of the len method will be zero.
In the first short version of your code this is not clear because the following line of code is missing in that version:
del viewsList[:]
After appending the viewList to masterViewList, this line of code causes the masterViewlist being empty again. This is because the del command deletes all references to this viewList including the one in the masterViewlist. You can remove this del of the viewList because you starts with a new viewList every time you are back in the beginning of the outer for loop.

Get value from query string in Python 3 without the [' '] showing up in the value

I have the following code in a Python 3 http server parse out a URL and then parse out a query string:
parsedURL = urlparse(self.path)
parsed = parse_qs(parsedURL.query)
say that parsedURL.query in this case turns about to be x=7&=3.I want to get the 7 and the 3 out and set them equal to variables x and y. I've tried both
x = parsed['x']
y = parsed['y']
and
x = parsed.get('x')
y = parsed.get('y')
both of these solutions come up with x = ['7'] and y = ['3'] but I don't want the brackets and single quotes, I want just the values 7 and 3, and I want them to be integers. How do I get the values out and get rid of the brackets/quotes?
Would simply:
x = int(parsed['x'][0])
y = int(parsed['y'][0])
or
x = int(parsed.get('x')[0])
y = int(parsed.get('y')[0])
serve your purpose? You should of course have suitable validation checks, but all you want to do is convert the first element of the returned array to an int, so this code will do the business.
This is because the get() returns an array of values (I presume!) so if you try parsing url?x=1&x=2&x=foo you would get back a list like ['1', '2', 'foo']. Normally there is only one (or zero, of course) instance of each variable in a query string, so we just grab the first entry with [0].
Note the documentation for parse_qs() says:
Data are returned as a dictionary. The dictionary keys are the unique query variable names and the values are lists of values for each name.

python3 string to variable

I am currently trying to implement Conway's Game of Life in a Code, and therefore built a function which generates the coordinates depending of the size of the window.
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = []
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords.append ('x'+str(n)+'y'+str(i))
return coords
Yet, I would like to randomly assign values to the resulting strings, to mark them either as alive (1) or dead (0). However they only way to convert a string to a variable name known to me is via a dict and var(), but however, it is essential for the further code that the coordinates stay sorted, as I want to be able to iterate over the ordered items and put the cursor accordingly to the coordinates name. Something like:
print ('\033['+X_COORD+';'+Y_COORD+'f'+ x1y5)
if e.g. x1y5 is the corresponding value (0 or 1) of the variable
Is there a convenient method how to either do this via a dict or how to convert the name of the strings to variable names?
Or probably. If I keep one dict and one list and store the coordinate names in the list and the values in the dict?
Thank you in advance!
kyril
You use a dictionary:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = {}
for i in range (0,num_y, 1):
for n in range (0,num_x,1):
coords['x'+str(n)+'y'+str(i)] = 0
return coords
You then access the value with
coords[x][y]
And change it like so:
coords[x][y] = 1
Now, of course this converting of coordinates to strings is completely pointless. Simply use a list of lists:
def coords_maker(num_x, num_y):
num_x += 1
num_y += 1
coords = [[0]*num_x for x in range(num_y)]
return coords
And I don't know why you add 1 to the coordinates either:
def coords_maker(num_x, num_y):
return [[0]*num_x for x in range(num_y)]

Resources