如何在Python中返回多个值? [英] How to return multiple values in Python?

查看:170
本文介绍了如何在Python中返回多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想知道这是否可能。所以,我需要发生的是让我的函数返回一个字符串。现在棘手的部分是,我的功能打印出一个奇特的模式,我不知道我怎样才能返回我的模式作为一个字符串?我不希望它在我使用函数之前打印任何东西,例如:

  my_function(c,r)
x = 4
y = 5
a = my_function(x,y)
print(a)

输出:

  *这里没有空格* 
*模式印出*

以下是my_function函数的代码:

def my_function(c,r):
if(c> 0 and r> 0):

print(**) c)

为范围内的(r - 2):
if(c == 1):
print(*)
elif(c> ; 1):
print(*+*(c - 2)+*)

if(r> 1):
print( ** c)

如果我按原样调用函数,它将打印所有内容。但我不希望它打印。我尝试用return来替换所有的打印文件,但是它只打印第一行(这并不意外,因为return只是在第一行终止了函数)。 class =h2_lin>解决方法

收集值返回到一个列表中,在函数结尾处构建一个字符串以返回:

  def my_function(c,r):
lines = []
如果c和r:
lines.append(** c)

对于我在范围(r - 2):
如果c == 1:
lines.append(*)
else:
lines.append(*+ *(c - 2)+*)

if r> 1:
lines.append(** c)

return'\\\
'.join(lines)

这包括相同的换行符, print()函数会在每行之间写入。



演示:

 >>> print(my_function(4,5))
****
* *
* *
* *
****


So I'm wondering if this is possible. So, what I need to happen is to make my function return a string. Now the tricky part is that my function prints out a fancy pattern and I'm not sure how I can return my pattern as a string? I don't want it to actually print anything before I use the function in something like:

my_function(c,r)  
x = 4
y = 5  
a = my_function(x,y)
print(a)

Output:

*nothing here blank space*
*pattern printed*

Here is my code for the function my_function:

def my_function(c, r):  
    if(c > 0 and r > 0):

        print("*" * c)

        for i in range(r - 2):
            if(c == 1):
                print("*")
            elif(c > 1):
                print("*" + " " * (c - 2) + "*")

        if(r > 1):
            print("*" * c)

If I call the function as is, it will print everything. But I don't want it to print. I tried replacing all the print by return but it prints only the first line(which was not unexpected, since return will just terminate the function at line 1).

解决方案

Gather the values to return into one list, build a string at the end of your function to return:

def my_function(c, r):  
    lines = []
    if c and r:
        lines.append("*" * c)

        for i in range(r - 2):
            if c == 1:
                lines.append("*")
            else:
                lines.append("*" + " " * (c - 2) + "*")

        if r > 1:
            lines.append("*" * c)

    return '\n'.join(lines)

This includes the same newlines the print() function would write between each line.

Demo:

>>> print(my_function(4, 5))
****
*  *
*  *
*  *
****

这篇关于如何在Python中返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆