1. 程式人生 > 其它 >python 遍歷刪除

python 遍歷刪除

技術標籤:python

1.

    a = [1, 2, 3, 4, 5, 6, 7, 8]
    # print(id(a))
    # print(id(a[:]))
    for i in a[:]:
        if i > 5:
            a.remove(i)
    print(a)
    # print(id(a))

2.filter

內建函式filter()官方文件參考:https://docs.python.org/3/library/functions.html#filter


  1. a = [1,2,3,4,5,6,7,8]

  2. b = filter(lambda x: x>5,a)

  3. print(list(b))

執行結果:

3.列表解析


  1. a = [1,2,3,4,5,6,7,8]

  2. b = [i for i in a if i >5]

  3. print(b)

執行結果: