Lists in a list - python

I am quite new to Python. I have a list containing some more lists, but only in two dimension (e.g. List[a][b]). Now for every value [a] I want to access a certain value [b] (10 in this case). For now it would be sufficent to just print every value List[a][10]. I tried:
for rec in List:
print List[rec][10]
That gives me the error "TypeError: list indices must be integers, not list". However if I just try "print List[0][10]" it gives me the value I want. In my for-Loop isn't rec an integer? How could I solve this problem?
Additional info: I am using Python 2.4.3 to be able to use the shapefile library that lets me access GIS data (my list).

for rec in List:
print rec[10]
should work.

You need to use:
for rec in List:
print rec[10]
or
for i range(len(List)):
print List[i][10]

rec in your case is not an integer, it is the first item of list. For you to use it as an integer you must add range in the for loop, like "for rec in range(0,len(List))"

Related

With python How to get only the indices of list items and use them as a variable in f-string

I'm trying to get selenium to click specific buttons on a website.
To do that I need the indices of list items to be a variable in a f-string.
Is there a neat way to access the indices of that list and declare them a variable? I know you can get both values, index and itemvalue of a list by enumerate, but maybe theres another way than converting the index strings into integers and work on with these.
Thats what I got so far:
T3 = browser.find_elements_by_xpath("//*[#id='tabelle_merkliste']/tbody/tr[position()<25]/td[10]/img/following::td[2]")
verf3string = []
for i in T3: # retrieve textelement
print(i.text)
textelement = i.text.split('/')
plätze = textelement[0] # only retrieve first position of string
print(plätze)
verf3string.append(plätze) #safe text in list
print(verf3string)
for i in range(len(verf3string)): # converting string list into list of integers to be able to compare numbers by </>
verf3 = (verf3string[i])
print(verf3)
for i in (verf3):
if i > 0:
x = verf3.index(i)
browser.find_element_by_xpath(f'//*[#id="tabelle_merkliste"]/tbody/tr{x}/td{y}/img').click()
#this gives me the error TypeError: '>' not supported between instances of 'str' and 'int'
By Any help is appreciated, thanks!
By enumerate I meant using it to retrieve indeces. It gives me the index plus value.
for index, value in enumerate(test_list):
print(index, value)
(
You can just retrieve the index of the item in a list (called 'array' here) like this:
x = array.index(i)
Or just do it in the f-string:
f'//*[#id="tabelle_merkliste"]/tbody/tr{array.index(i)}/td{y} /img'

Python: Randomly Select One Key From All Keys in a Dictionary

Let's say I have accessed my dictionary keys using print (hamdict.keys())
Below is a sample output:
I know my dictionary list has a length of 552 elements. I want to randomly select one "key" word from my list and assign it to the variable "starter". I tried to do this with the code below (note: I have a dictionary called hamdict):
random_num = random.randint(0, len(hamdict.keys())-1)
print (random_num)
print (hamdict.keys()[random_num])
I'm able to get a value for random_num so that seems to work. But the second print returns the following error:
How can I fix my code?
my_dictionary.keys() returns a generator-like object, not a list. You can probably get what you want by converting it to a list first
print(list(hamdict.keys())[random_num])
Try this:
random.sample(hamdict.keys(),1)[0]
The sample() function randomly selects a given number of items from a list or iterator. Contrary to the choice function, it supports iterators so you don't need to make a list out of the keys beforehand. The result is a list so you need to get its first item from the output (hence the [0]).

Enumerate - Python loop

I have two lists with just one element as follows(each of these two lists always contains only one element):
Vnew = [600]
Newoints2 = [(2447,3480)]
I'm trying to bring both of them together using the following code sample:
for i, key in enumerate(Vnew2):
pos3[key] = newpoints2[i]
But this returns an error as IndexError: list assignment index out of range
I actually did this one for other lists which have more than one element. It worked fine and got the output as {0:(1245,674),1:(2457,895),...}
Can someone find the mistake here?
It looks like you are trying to concatenate the lists into a new list. You don't always need to enumerate through the list.
You will be able to do this by Vnew + Newoints2

Python list - string formatting as list indices

Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple If ... Else statement. I tried to use %s string formatting but it won't work. Below code, so it will become more clear what I try to do:
if condition:
item = my_list['%s']
else:
item = my_other_list['%s']
# now I do something with this value:
print item % 3
This way I tried to print 3rd value of one or other list if the condition was True of False. This returned an error about list indices being string. So I tried to put it inside int() what didn't help.
How should I do it? The problem is I get the value later than I declare what item is.
EDIT
I will add some more infos here:
I have a for loop, that goes through ~1000 elements and processes them. If the condition is True, it calls one function or another if false. Now, I don't want to check the same condition 1000 times, because I know it won't change during the time and would like to check it once and apply the method to all of the elements.
More code:
if self.dlg.comboBox_3.currentIndex == 0:
item = QCustomTableWidgetItem(str(round((sum(values['%s'])/len(values['%s'])),2)))
else:
item = QCustomTableWidgetItem(str(round(sum(values['%s'],2))))
for row in range(len(groups)):
group = QTableWidgetItem(str(groups[row]))
qTable.setItem(row,0,group)
qTable.setItem(row,1,item % row)
This is the actual code. Not the '%s' and '% row'. I used simplified before not to distract from the actual problem, but I think it's needed. I'm sorry if it wasn't a good decision.
You have a reasonably large misconception about how list slicing works. It will always happen at the time you call it, so inside your if loop itself Python will be trying to slice either of the lists by the literal string "%s", which can't possibly work.
There is no need to do this. You can just assign the list as the output from the if statement, and then slice that directly:
if condition:
list_to_slice = my_list
else:
list_to_slice = my_other_list
# now I do something with this value:
print list_to_slice[3]
Short answer:
'%s' is a string by definition, while a list index should be an integer by definition.
Use int(string) if you are sure the string can be an integer (if not, it will raise a ValueError)
A list is made up of multiple data values that are referenced by an indice.
So if i defined my list like so :
my_list = [apples, orange, peaches]
If I want to reference something in the list I do it like this
print(my_list[0])
The expected output for this line of code would be "apples".
To actually add something new to a list you need to use an inbuilt method of the list object, which looks something like this :
my_list.append("foo")
The new list would then look like this
[apples, orange, peaches, foo]
I hope this helps.
I'd suggest wrapping around a function like this:
def get_item(index, list1, list2)
if condition:
return list1[index]
else:
return list2[index]
print get_item(3)
Here is a compact way to do it:
source = my_list if condition else my_other_list
print(source[2])
This binds a variable source to either my_list or my_other_list depending on the condition. Then the 3rd element of the selected list is accessed using an integer index. This method has the advantage that source is still bound to the list should you need to access other elements in the list.
Another way, similar to yours, is to get the element directly:
index = 2
if condition:
item = my_list[index]
else:
item = my_other_list[index]
print(item)

Python: Adress sub-tuples in tuple of tuples?

Hy!
As a complete beginner to python I wonder how I fetch a tuple-element inside a tuple of tuples - i.e. the result of
results=cursor.fetchall()
gives a tuple
((row1_value1,row1_value2,...),(row2_value1,row2_value2..),)
I know that
for id in results:
print id
or
results [i]
accesses each row as a whole.
But how do I directly access a tuple - value inside the tuple, i.e. row2_value3 ???
I helped myself with the following code, but isn´t there a possibility to give a exact "adress", such as
results [i,sub-i] ??
for id in results:
a=results[i]
i=0
for x in a:
print a[i]
i+=1
I want to use fetchall, just to learn how to do things in python- i want to have the whole datbase in python and work with that.
Thanks a lot!
results[0][1]
accesses the second (1) element from the first (0) row (row1_value2 in your case). The lists in Python are 0-indexed.
The same way, row2_value3 is results[1][2]
You can just do results[row][field].

Categories

Resources