python 遍歷刪除
阿新 • • 發佈:2021-01-13
技術標籤: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
-
a = [1,2,3,4,5,6,7,8]
-
b = filter(lambda x: x>5,a)
-
print(list(b))
執行結果:
3.列表解析
-
a = [1,2,3,4,5,6,7,8]
-
b = [i for i in a if i >5]
-
print(b)
執行結果: