简体   繁体   English

从函数返回多个输出

[英]Returning multiple outputs from function

I am not sure that this is possible, but... 我不确定这是否可能,但是...

I am trying to write a function that will output lists of numbers so that they can be input into another function. 我正在尝试编写一个将输出数字列表的函数,以便可以将它们输入到另一个函数中。 I'm at a dead end though, as neither return or yield (used in this context) can give me what I want. 不过,我处于死胡同,因为returnyield (在此上下文中使用)都无法满足我的需求。

def ITERATOR():
    for number in range(1,3):
        for item in itertools.permutations(range(15),number):
            yield item

Obviously, the function breaks whenever return is used, and yield returns everything at once. 显然,只要使用return ,函数就会中断, yield返回所有内容。 What I ideally want it to output is what is printed on each line by: 我理想地希望它输出的是通过以下方式在每行上打印的内容:

def ITERATOR():
    for number in range(2,4):
        for item in itertools.permutations(range(15),number):
            print(item)

ie: 即:

(0, 1)
(0, 2)
(0, 3)
(0, 4)
(0, 5)
(0, 6)
(0, 7)
(0, 8)
(0, 9)
(0, 10)
(0, 11)
(0, 12)
(0, 13)
(0, 14)
etc...

Is there any way of achieving this? 有什么办法可以做到这一点?

If you want to return a list, you could just do it: 如果要返回列表,可以执行以下操作:

def fct():
    return [item for item in itertools.permutations(range(15),number) for number in range(2,4)]

And for a generator 对于发电机

def fct():
    return (item for item in itertools.permutations(range(15),number) for number in range(2,4))

Solution

new_tuples = []
for i in range(0, 5):
    for j in range(1, 16):
        new_tuples.append((i, j))

for i in new_tuples:
    print(i)

Output 产量

 (xenial)vash@localhost:~/python$ python3 text_seg.py (0, 1) (0, 2) (0, 3) (0, 4) (0, 5) (0, 6) (0, 7) (0, 8) (0, 9) (0, 10) (0, 11) (0, 12) (0, 13) (0, 14) (0, 15) (1, 1) 

Comments 评论

Would this approach satisfy your needs? 这种方法会满足您的需求吗? You could interchange the numbers as desired but this, will allow you to have a list with the tuples store and be able to call them to print . 您可以根据需要交换数字,但这将允许您在tuples存储中有一个list ,并能够调用它们进行print

You can return the list through the argument of the function, and use the return of the function to indicate the number of permutations founded: 您可以通过函数的参数返回列表,并使用函数的返回值指示建立的排列数:

import itertools

permut = []

def ITERATOR(item):
    n_permuts= 0
    for number in range(2,4):
        for item in itertools.permutations(range(15),number):
            permut.append(item)
            n_permuts+= 1
    return n_permuts

print (ITERATOR(permut))
for item in permut:
    print(item)

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

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