0

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.

adamczi
  • 343
  • 1
  • 7
  • 24
  • 1
    lists require integer indexes; The first element is always 0. For example, if you want to access the 3rd element of a list you can do so with `my_list[2]` Therefore, unless `%s` is an integer, you aren't using these lists correctly. – Daniel Lee Sep 05 '16 at 11:14
  • I don't really understand this comment - the indice will surely be an integer ('3' in the example), but the `'%s'` is a string. I hoped the nature of this '%s' string will make the indice an integer as an int = 3 is being passed later. – adamczi Sep 05 '16 at 11:22
  • 1
    Try and make your code more explicit. Surely you don't expect the `print item %3` to affect the result of the `if...else` statement as determined previously? – Daniel Lee Sep 05 '16 at 11:26
  • Still I have no no clue what `%s` comes from? It is (should be) a list index. – Jacob Vlijm Sep 05 '16 at 11:36
  • well, I know this won't work - my question is about how to kind of affect this `if` but in a correct way. could be a totally different one though. – adamczi Sep 05 '16 at 11:37
  • There is a code update, that I would appreciate you look at. – adamczi Sep 05 '16 at 11:44
  • Is that updated snippet working? Do you get something for `item`? I am asking because it should not since the list slicing is done wrong. However, they might have implemented their own generator since it does not seem to be a default datatype then.... – albert Sep 05 '16 at 16:35
  • No, it doesn't work, it's the actual code I want to correct. I wrote this `%s` thing just to show what I would like to get- something similar to regular `print 'name: %s' % 'Tom'` but for integer as list indice. Seems I can't really explain it clear, I was just asking about similar system. – adamczi Sep 05 '16 at 22:45

5 Answers5

2

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]
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

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)

Community
  • 1
  • 1
Jacob Vlijm
  • 3,099
  • 1
  • 21
  • 37
  • do you mean `item = my_list[int('%s')]` ? as I wrote I tried that already and it gives `ValueError: invalid literal for int() with base 10: '%s'` – adamczi Sep 05 '16 at 11:19
  • @adamczi Ah, I missed that, What is the origin of `%s`? – Jacob Vlijm Sep 05 '16 at 11:21
  • Origin of `'%s'`? I'm trying to find a method that is similar to `'%s' % text_variable' but will work with list indices. – adamczi Sep 05 '16 at 11:48
0

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 really appreciate your effort, but your answer isn't quite related to the question. – Ahsanul Haque Sep 05 '16 at 11:19
  • 1
    I just want to mention that this code is for Python 3. So please keep that in mind since the OP used `print something` indicating using Python 2. – albert Sep 05 '16 at 11:20
  • @albert `print "string"` does not work in `python3`, but `print("string")` works fine in `python2` – Jacob Vlijm Sep 05 '16 at 12:29
  • That's right but semantically not the same as discussed here: http://stackoverflow.com/a/12162754/3991125 – albert Sep 05 '16 at 16:34
0

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)
albert
  • 8,027
  • 10
  • 48
  • 84
  • Thank you, but in my case this would get executed as many times as elements so that wouldn't be what I want. I posted code update there. – adamczi Sep 05 '16 at 11:45
0

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)
mhawke
  • 84,695
  • 9
  • 117
  • 138