简体   繁体   中英

Python for loop nested in if else loop

Can anyone help to solve my following question, sorry I might not express clearly in the title.

myList = ['val', 'val2', 'val3']

def myfunction():
    if condition1:
        topic = "string1"
    elif condition2:
        topic = "string2"
    elif condition3:
        for val in myList:
            topic = string3.replace('str', val)
    else:
        topic = "string4"
    return topic

When condition3 is met, myfunction will only return the last value of myList . In this case, how to make the code return all combinations of "string3" + value in myList ?

Please advise. Thanks

==Edit==

Edited code in question

I would like the function to return

valing3
val2ing3
val3ing3
myList = ['val', 'val2', 'val3']

def myfunction():
    if condition1:
        topic = "string1"
    elif condition2:
        topic = "string2"
    elif condition3:
        topic = "string3"
        for val in myList:
            topic = topic + val 
    else:
        topic = "string4"
    return topic

Use:

myList = ['val', 'val2', 'val3']

def myfunction():
    if condition1:
        topic = "string1"
    elif condition2:
        topic = "string2"
    elif condition3:
        topic = ["string3" + val for val in myList]
    else:
        topic = "string4"
    return topic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM