mercredi 5 mai 2021

Python Selecting the other item in a 2-item list

I have a list with two items. I would like to iterate over this list to avoid duplicating very similar code:

for item in ["str1", "str2"]
    if <condition>:
        var1 = item
    else:
        var1 = <the "other" item in the list>
    
    #other code that depends on var1 and on item

In the first iteration, if we end up in the else branch, var1 should be assigned the value "str2", while in the second iteration, var1 would be assigned "str1".

The only way I can think of solving this is without a loop, i.e, repeating my code. Is there a way I can keep the loop?

Thank you

EDIT1: Added the fact that the code within the loop has statements that use both var1 and item.

EDIT2: Here's a less psuedo-code like example of what I'm trying to do: EDIT3: The append doesn't directly use item. I've added a bit more:

myList = ["str1", "str2"]
outList = []
isSame = True # or False
for item in myList:
    val1 = item if isSame else #the other item
    str3 = "some text {0} some more text {1}".format(item, val1)
    outList.append(str3)

Without a loop, this would look like:

item = "str1"
val1 = "str1" if isSame else "str2
str3 = "some text {0} some more text {1}".format(item, val1)
outList.append(str3)

item = "str2"
str3 = "some text {0} some more text {1}".format(item, val1)
outList.append(str3)

Aucun commentaire:

Enregistrer un commentaire