【问题标题】:Drop an element from a list (drop row from list of lists)从列表中删除元素(从列表列表中删除行)
【发布时间】:2017-08-30 01:20:21
【问题描述】:

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

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' 的行感兴趣。例如:

  • Joe 在其数据的第二次出现中的索引 2 处具有值 '2TM'
  • Tom 在其数据第一次出现时的索引 2 处具有值 '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]

【问题讨论】:

    标签: python list if-statement conditional remove-if


    【解决方案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 的增量。

    【讨论】:

    • list.pop 如果在包含 '2TM' 的行之后没有两行(甚至一行),则将失败。例如,如果list_of_data 的最后一行(或倒数第二行)包含'2TM',则list.pop 将引发异常。
    • 他提到接下来的两行需要删除。虽然可以对最后一行应用检查
    • @ZachGates 我理解你的反对意见。出于一般目的,您是对的:这种方法会在您描述的场景中引起反对。但是,我的数据集的固有/独特性是,每当 2TM 出现在我的数据中时,总会有 2 行需要删除。所以这个 .pop 方法实际上适用于我的数据,即使它可能不适用于一般用途。
    【解决方案2】:

    使用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
    

    【讨论】:

    • 这种方法和下面的方法一样有效。非常感谢您的意见。