将可变长度作为参数并返回元组的函数



我已经编写了代码:

def convTup(*args):
    t = set([])
    for i in args:
        t.add(i)
    return tuple(t)
print convTup('a','b','c','d')
print convTup(1,2,3,4,5,6)
print convTup('a','b')

预期输出:

('a', 'b', 'c', 'd')
(1, 2, 3, 4, 5, 6)
('a', 'b')

,但我的输出如下:

('a', 'c', 'b', 'd')
(1, 2, 3, 4, 5, 6)
('a', 'b')

为什么元素的顺序仅适用于('a','b','c','d')?如何以与给定输入相同的顺序打印元组?

您可以使用它,并且将元组序列作为输入

>>> def f(*args):
    p = []
    [p.append(x) for x in args if x not in p]
    return tuple(p)
>>> f(1, 1, 2, 3)
(1, 2, 3)
>>> f('a', 'b', 'c', 'd')
('a', 'b', 'c', 'd')

此功能将创建唯一元素的列表并跟踪其顺序然后将其返回为元组。

您可以使用 set 而不是 list 看到相同的功能。一组不会跟踪输入元素的顺序。

>>> def tup1(*args):
    l = {x for x in args}
    return tuple(l)
>>> 
>>> tup1('a', 'b', 'c', 'd')
('a', 'c', 'b', 'd')

您可以在多个位置使用自己的 sortedset 集合。

这应该做您需要的事情:

def convTup(*args):
    return sorted(tuple(set(args)), key=lambda x: args.index(x))

sou您将args转换为默认情况下排序的 set,然后将其转换为 tuple,最后按原始顺序对 tuple进行排序。

因此,确切地说,此功能仅考虑到Args中的元素的首次外观。

最新更新