简体   繁体   English

给定递归 function,如何返回具有唯一元素的元组

[英]How can I return a tuple with unique elements given a recursive function

I have looked around in other posts and haven't been able to come to a solution for this.我查看了其他帖子,但未能找到解决方案。 I have a function that needs to be recursively called using an itertools expression in order to return a tuple that has unique elements with it's order preserved.我有一个 function 需要使用 itertools 表达式递归调用,以便返回具有唯一元素并保留其顺序的元组。

for instance:例如:

def function(list):
    return list and (list[0],) + function(some_itertools_expression)

given example: function([1, 7, 7, 9, 0, 1]) should return (1, 7, 9, 0)给定的例子: function([1, 7, 7, 9, 0, 1])应该返回(1, 7, 9, 0)

I've tried using:我试过使用:

return list and (list[0],) + function(tuple([itertools.groupby(list)][:len(list)]))

but I end up running into RecursionError: maximum recursion depth exceeded .但我最终遇到了RecursionError: maximum recursion depth exceeded How can I solve this without getting the max recursion depth error?如何在没有最大递归深度错误的情况下解决这个问题?

You can do this fairly easily, without needing recursion, by making a tuple via dictionary keys.你可以很容易地做到这一点,不需要递归,通过字典键创建一个元组。 The dict must have unique keys, and will preserve the order of the original input sequence. dict 必须有唯一的键,并且会保留原始输入序列的顺序。

>>> data = [1, 7, 7, 9, 0, 1]
>>> (*{}.fromkeys(data),)
(1, 7, 9, 0)

If you must use a function from itertools in a recursive call, I would grab the first item of the sequence in each recursion and use itertools.filterfalse to filter items equal to the first from the sequence returned by a recursive call with the rest of the items:如果您必须在递归调用中使用itertools中的 function,我会在每次递归中获取序列的第一项,并使用itertools.filterfalse过滤等于递归调用返回的序列中的第一项的项 rest 的项目:

from itertools import filterfalse

def unique(lst):
    if not lst:
        return ()
    first, *rest = lst
    return first, *filterfalse(lambda i: i == first, unique(rest))

print(unique([1, 7, 7, 9, 0, 1]))

This outputs:这输出:

(1, 7, 9, 0)

Demo: https://replit.com/@blhsing/WelloffPlainAutomaticparallelization演示: https://replit.com/@blhsing/WelloffPlainAutomaticparallelization

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

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