简体   繁体   English

将 python 列表作为 function 参数传递

[英]Passing python list as an function argument

I have the below python code我有以下 python 代码

def fir(a,x):
    for i in x:
        h = getx(a,i)
        return h
def getx(a, i):
    print('Hello {} {}'.format(a, i))

print(fir(2,['hi','Helloooooooooooooooo']))

o/P gives me as o/P 给我作为

Hello 2 hi
None

I dont want None but instead i need我不想要 None 但相反我需要

Hello 2 Helloooooooooooooooo

Why is it showing as None?为什么显示为无?

When you return after a loop, make sure that the 'return' code falls outside of the loop.当您在循环后返回时,请确保“返回”代码位于循环之外。 Otherwise, you'll only return the first iteration.否则,您只会返回第一次迭代。 See your code updated below:请参阅下面更新的代码:

def fir(a,x):
    for i in x:
        h = getx(a,i)
    return h
def getx(a, i):
    print('Hello {} {}'.format(a, i))

print(fir(2,['hi','Helloooooooooooooooo']))

Note that the "return h" line is now in line with the for loop, rather than inside it.请注意,“return h”行现在与 for 循环一致,而不是在其中。

You're return -ing at the end of the first loop iteration, so the code only sees "hi".您在第一次循环迭代结束时return -ing,因此代码只看到“hi”。

Take return out of the loop. return排除在循环之外。 Collect all the results of getx() in a list and join them in the returned value.getx()的所有结果收集到一个列表中,并将它们加入到返回值中。

And getx() should return the formatted string rather than printing it, so that the caller can print the result itself. getx()应该返回格式化的字符串而不是打印它,以便调用者可以自己打印结果。

def fir(a,x):
    return "\n".join(getx(a, i) for i in x)
def getx(a, i):
    return 'Hello {} {}'.format(a, i)

print(fir(2,['hi','Helloooooooooooooooo']))

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

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