我有一个像这样的二维数组:
list_of_data = [
['Joe', 4, 4, 4, 5, 'cabbage', None],
['Joe', 43, '2TM', 41, 53, 'cabbage', None],
['Joe', 24, 34, 44, 55, 'cabbage', None],
['Joe', 54, 37, 42, 85, 'cabbage', None],
['Tom', 7, '2TM', 4, 52, 'cabbage', None],
['Tom', 4, 24, 43, 52, 'cabbage', None],
['Tom', 4, 4, 4, 5, 'cabbage', None],
['Fred', 4, 4, 4, 5, 6, 'cabbage'],
['Fred', 4, 4, 4, 5, 6, 'cabbage'],
['Fred', 4, 4, 4, 5, 6, 'cabbage'],
]
我对第2个索引处包含值'2TM'
的行感兴趣。例如:
'2TM'
。'2TM'
。 每次值'2TM'
出现在数据中时,我想删除接下来的两行。上面的例子将成为以下内容:
list_of_data =
['Joe', 4, 4, 4, 5, 'cabbage', None],
['Joe', 43, '2TM', 41, 53, 'cabbage', None],
['Tom', 7, '2TM', 4, 52, 'cabbage', None],
['Fred', 4, 4, 4, 5, 6, 'cabbage'],
['Fred', 4, 4, 4, 5, 6, 'cabbage'],
['Fred', 4, 4, 4, 5, 6, 'cabbage'],
]
我尝试过像这样使用list.pop
:
for row[x] in list_of_data:
if '2TM' in row:
list_of_data.pop[x+1:x+2]
答案 0 :(得分:1)
你需要做这样的事情
list_of_data = [['Joe', 4, 4, 4, 5, 'cabbage', None],
['Joe', 43,'2TM', 41, 53, 'cabbage', None],
['Joe', 24, 34, 44, 55, 'cabbage', None],
['Joe', 54, 37, 42, 85, 'cabbage', None],
['Tom', 7,'2TM', 4, 52, 'cabbage', None],
['Tom', 4, 24, 43, 52, 'cabbage', None],
['Tom', 4, 4, 4, 5, 'cabbage', None],
['Fred', 4, 4, 4, 5, 6, 'cabbage'],
['Fred', 4, 4, 4, 5, 6, 'cabbage'],
['Fred', 4, 4, 4, 5, 6, 'cabbage']]
x=0
for row in list_of_data:
if '2TM' in row:
list_of_data.pop(x+1)
list_of_data.pop(x+1)
x+=1
print(list_of_data)
你很接近,但错过了x的增量。
答案 1 :(得分:1)
使用while
循环:
index = 0
while index < len(list_of_data):
if list_of_data[index][2] == '2TM':
# check if the names are the same, as needed
del list_of_data[index + 1:index + 3]
index += 1