简体   繁体   English

Python:For 循环无法正常工作

[英]Python: For loop not working properly

Why is the for loop not working properly?为什么 for 循环不能正常工作? It's just returned only one element.它只返回了一个元素。

1. 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. 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.您最大的问题是您返回 for 循环第一次迭代的结果,而不是在 for 循环完成之后。

Another issue is that strings cannot be reversed with the reverse() method.另一个问题是字符串不能用 reverse() 方法反转。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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