我收集了這樣的串列:
example = [['a','b','c'],['d','e','f'],[ ],['z'],['g','h','i'],[ ],['z']]
我想從串列中洗掉[]和。['z']所需的輸出是:
example = [['a','b','c'],['d','e','f'],['g','h','i']]
我該怎么做?我可以使用一個襯墊去除兩者嗎?我熟悉.pop()和.remove()命令,但我懷疑它是否適用于 [ ] 型別的串列。
uj5u.com熱心網友回復:
您可以使用串列推導進行過濾:
example = [['a','b','c'],['d','e','f'],[ ],['z'],['g','h','i'],[ ],['z']]
output = [sublst for sublst in example if sublst not in ([], ['z'])]
print(output) # [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
uj5u.com熱心網友回復:
一些可能性:
example = [['a','b','c'],['d','e','f'],[ ],['z'],['g','h','i'],[ ],['z']]
example.remove([])
example.remove([])
example.remove(['z'])
example.remove(['z'])
要么
del example[2]
del example[3]
del example[5]
del example[-1]
要么
example = [i for i in example if i != [] and i != ['z']]
要么
for i in range(len(example)-1, 0,-1):
if example[i] in ([],['z']):
del example[i]
uj5u.com熱心網友回復:
你可以像這樣洗掉它們:
example = list(filter(lambda val: val != [] and val!=['z'], example))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441608.html
