adamczi
adamczi

Reputation: 355

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.

Upvotes: 0

Views: 2572

Answers (5)

mhawke
mhawke

Reputation: 87074

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)

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599600

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]

Upvotes: 2

albert
albert

Reputation: 8593

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)

Upvotes: 0

Brandon Jones
Brandon Jones

Reputation: 31

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.

Upvotes: 0

Jacob Vlijm
Jacob Vlijm

Reputation: 3159

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)

Upvotes: 0

Related Questions