2

Currently I have a list with some non-repeating positive integers in it say a = [1,2,6,15,19]

What is the most idiomatic way to create a function that returns a new list that is the result of taking the modulo %x of each element of a without having any repeated elements in the output?

Specifically I want f(a,x) to return [1%x,2%x,6%x,15%x,19%x] without the repeated elements.

For example f([1,2,6,15,19],4) would return [1,2,3]

4

2 回答 2

6

使用列表推导和 aset()过滤掉重复项并保持顺序:

def f(values, x):
    seen = set()
    add = seen.add
    return [res for res in (i % x for i in values) if res not in seen and not add(res)]

演示:

>>> f([1,2,6,15,19], 4)
[1, 2, 3]

如果不需要保留顺序,只需使用集合推导并返回结果集:

def f(values, x):
    return {i % x for i in values}
于 2013-08-01T15:12:34.150 回答
4

要返回集合列表,您需要一个包含在列表中的集合理解。

def f(l, x):
    return list({i % x for i in l})

根据问题评论,返回集合可能是最好的选择。

def f(l, x):
    return {i % x for in l}
于 2013-08-01T15:13:13.950 回答