首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从列表中删除元素(从列表中删除行)

从列表中删除元素(从列表中删除行)
EN

Stack Overflow用户
提问于 2017-08-30 01:20:21
回答 2查看 758关注 0票数 1

我有一个像这样的二维数组:

代码语言:javascript
复制
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'的第二个索引的行感兴趣。例如:

  • 乔的数据第二次出现在索引2处,其值为'2TM'
  • 在数据的第一次出现时,Tom的值在索引2处。

每次'2TM'值出现在数据中时,我都希望删除接下来的两行。上面的例子如下:

代码语言:javascript
复制
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

代码语言:javascript
复制
for row[x] in list_of_data:
    if '2TM' in row:
        list_of_data.pop[x+1:x+2]
EN

回答 2

Stack Overflow用户

发布于 2017-08-30 01:35:54

你需要这样做

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2017-08-30 01:38:13

使用while循环:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45950485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档