简体   繁体   English

从列表中删除子列表

[英]Delete sublist from a list

I want to delete a sublist from a list. 我想从列表中删除子列表。 I only know the starting index and the ending index. 我只知道起始索引和结束索引。 how can I delete from the list? 如何从列表中删除?

I'm using the following code: 我正在使用以下代码:

def delete_sub_list( self, cmd_list, start, end ):
        tmp_lst = []
        for i in range( len( cmd_list ) ):
            if( i < start or i > end ):
                tmp_lst.append( cmd_list[ i ] )

        return tmp_lst

and I'm calling in the following way: 我用以下方式打电话:

cmd_list = self.delete_sub_list( cmd_list, 4, 14 )

The Python syntax to do this is 执行此操作的Python语法是

del cmd_list[4:14 + 1]

(The + 1 is necessary to match your code. Python uses half-open intervals, ie the first index is included in the slice, but the last isn't.) + 1是匹配你的代码所必需的.Python使用半开区间,即第一个索引包含在切片中,但最后一个不是。)

You can use either: 你可以使用:

cmd_list[start:end + 1] = []

or 要么

del cmd_list[start:end + 1]

Might be easiest to do it with slicing: 切片可能最容易做到:

cmd_list = cmd_list[:start] + cmd_list[end+1:]

we still need end+1 for the second half, but it's still a pretty clear line of code. 我们仍然需要在下半场结束+ 1,但它仍然是一个非常清晰的代码行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM