码迷,mamicode.com
首页 > 其他好文 > 详细

[1].Array.diff

时间:2020-06-21 23:07:28      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:元素   lang   present   blog   log   python   转换   示例   loading   

Description

Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.

  • It should remove all values from list a, which are present in list b,such as array_diff([1,2],[1]) == [2]
  • If a value is present in b, all of its occurrences must be removed from the other: such as array_diff([1,2,2,2,3],[2]) == [1,3]

Solution

my code

def array_diff(a, b):
    for num in b:
        while num in a:
            a.remove(num)
    return a

others‘ code

def array_diff(a, b):
    return [x for x in a if x not in b]
def array_diff(a, b):
    return [x for x in a if x not in set(b)]
def array_diff(a, b):
    #your code here
    return filter(lambda i: i not in b, a)

Conclusion

  • set()具有去重功能

  • 列表推导式

  • list & dict & set的时间复杂度
    技术图片
    技术图片
    技术图片

  • filter(function,iterable)用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用list()来转换

fliter使用示例

#过滤出列表中的奇数
def is_odd(n):
    return n % 2 == 1 
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
newlist = list(tmplist)
print(newlist)
#过滤出1~100内的平方数
import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0 
tmplist = filter(is_sqr, range(1, 101))
newlist = list(tmplist)
print(newlist)

备注:部分内容参考这个博客,仅供学习交流使用,侵删。

[1].Array.diff

标签:元素   lang   present   blog   log   python   转换   示例   loading   

原文地址:https://www.cnblogs.com/zjx-pku/p/13174177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!