我有一个像这样的二维数组:
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'],
]我对包含值'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]发布于 2017-08-30 01:35:54
你需要这样做
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的增量。
发布于 2017-08-30 01:38:13
使用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 += 1https://stackoverflow.com/questions/45950485
复制相似问题