简体   繁体   English

python-从列表中删除元素

[英]python- deleting of elements from a list

name = list('ayushgupta')
>>> name
['a', 'y', 'u', 's', 'h', 'g', 'u', 'p', 't', 'a']
>>> name[5:5] = list('THE')
>>> name
['a', 'y', 'u', 's', 'h', 'T', 'H', 'E', 'g', 'u', 'p', 't', 'a']
>>> name[5:5] = []
>>> name
['a', 'y', 'u', 's', 'h', 'T', 'H', 'E', 'g', 'u', 'p', 't', 'a']

If I try to delete 'T', 'H', 'E' from name using name[5:5], it doesn't work. 如果我尝试使用name [5:5]从名称中删除“ T”,“ H”,“ E”,则无法使用。 I know I can use name[5:8] to delete the same. 我知道我可以使用name [5:8]删除相同的名称。 Could anyone explain why this is so? 谁能解释为什么会这样?

You can change both the content and the length of a list by assigning to slice of the list. 您可以通过分配列表的一部分来更改列表的内容和长度。 However, your slice is name[5:5] . 但是,您的切片是name[5:5] Remember that a slice does not include the ending index . 请记住, 切片不包含结尾索引 Thus, your slice starts at name[5] and continues to but does not include name[5] . 因此,您的分片从name[5] ,一直到但不包括name[5] In other words, your slice is empty . 换句话说,您的切片是空的

In short, you are trying to delete a part of the list that already is empty. 简而言之,您正在尝试删除列表中已经为空的一部分。 If you try an actual slice, such as name[5:8] , you will be more successful. 如果您尝试实际切片,例如name[5:8] ,将会更加成功。 To delete just one item, try name[5:6] . 要仅删除一项,请尝试使用name[5:6] The length of slice name[a:b] is ba (if b is greater than or equal to a ), which is easy to remember. 切片name[a:b]的长度为ba (如果b大于或等于a ),这很容易记住。

You have to do: 你必须做:

>>> name[5:8] = []
>>> name
['a', 'y', 'u', 's', 'h', 'g', 'u', 'p', 't', 'a']

When you did, name[5:5]=list('THE') , THE got inserted into the list from 5th index to 5th index of list. 当你做了, name[5:5]=list('THE') THE得到了插入距离第五索引列表的第5索引列表。 When you are doing name[5:5] = [] , you are not deleting anything, instead trying to insert empty list , and hence no change. 当您执行name[5:5] = [] ,您没有删除任何内容,而是尝试插入空list ,因此没有更改。 For updating the items from list from 5 to 8 index, you have to do name[5:8] = [] 为了将列表中的项目从5索引更新到8索引,您必须执行name[5:8] = []

OR, you may use del to delete content for the list as: 或者,您可以使用del删除列表内容,如下所示:

>>> del name[5:8]
>>> name
['a', 'y', 'u', 's', 'h', 'g', 'u', 'p', 't', 'a']

See: 看到:

    name[5:5]

means: element from the index 5 (inclusive) to 5 ( exclusive ) 表示:从索引5 (包含)到5包含)的元素

So you have use something as 所以你用了一些东西

    name[4:5]

to select (by rather complicated way) element name[4] . 选择(以相当复杂的方式)元素name[4]

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

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