0
del rec[1][1]
這是從列表中刪除項目的方法嗎?使用'del'從python列表中刪除一個項目
[ ['a','b','c'],
['d','e','f'],
['g','h','i'] ]
我想刪除b,e和h。我應該怎麼做?
del rec[1][1]
這是從列表中刪除項目的方法嗎?使用'del'從python列表中刪除一個項目
[ ['a','b','c'],
['d','e','f'],
['g','h','i'] ]
我想刪除b,e和h。我應該怎麼做?
你可以這樣做
# the main list of lists
list1 = [ ['a','b','c'], ['d','e','f'],['g','h','i'] ]
for x in xrange(len(list1)):
del_list = list1[x][1]
while del_list in list1[x]: list1[x].remove(del_list)
print((list1))
輸出
[['a', 'c'], ['d', 'f'], ['g', 'i']]
這是很容易去掉 'B', 'E' 和 'h'因爲這些條目恰好在list1的子列表的第二位。
您可以使用.pop(i)
方法,其中'我'是一個迭代器。
rec = [ ['a','b','c'],
['d','e','f'],
['g','h','i'] ]
for i in range (0, len(rec)):
print rec[i].pop(1)
請注意,.pop()
方法也返回該項目。 上面的代碼將導致:
b
e
h
看看'numpy.delete' –