简体   繁体   中英

Python: For loop not working properly

Why is the for loop not working properly? It's just returned only one element.

1.

rx = ['abc', 'de fg', 'hg i']
def string_m(a=rx):
     for i in a:
         l = re.sub(" ","/",i)
         r = l.split("/")
         r.reverse()
         rx = " ".join(r)
         return rx
a=string_m(rx)
print(a)

Outputs:

abc

2.

rx = ['abc', 'de fg', 'hg i']
def string_m(a=rx):
     for i in a:
         l = re.sub(" ","/",i)
         r = l.split("/")
         r.reverse()
         rx = " ".join(r)
     return rx
a=string_m(rx)
print(a)

Outputs:

i hg

-- Can someone help me to see what I am doing wrong?

import re

rx = ['abc', 'de fg', 'hg i']

def string_m(a=rx):
    new = []
    for i in a:
        l = re.sub(" ","/",i)
        r = l.split("/")
        #r.reverse()
        rx = " ".join(r)
        new.append(rx)
    new.reverse()
    return new

a=string_m(rx)
print(a)

Your biggest problem is that you return the result of the first iteration of your for loop instead of after the for loop has finished.

Another issue is that strings cannot be reversed with the reverse() method. If you want to reverse the output, Try the above.

rx = ['abc', 'de fg', 'hg i'] def string_m(a=rx): for i in range(len(a)): rx = a[i] return rx a=string_m(rx) print(a)

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