Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python-删除字符串中的一个字母_Python 3.x_List - Fatal编程技术网

Python 3.x Python-删除字符串中的一个字母

Python 3.x Python-删除字符串中的一个字母,python-3.x,list,Python 3.x,List,我想从字符串列表中删除一个变量(字符串)。所以基本上: list = ["A", "G", "T", "C"] number = 2 newlist = ["A", "G", "T", "C"] - list[number] 这应该是: newlist = ["A", "G", "C"] 但当我尝试此操作时,它会显示以下错误消息: Traceback (most recent call last): File "mini.py", line 3, in <module>

我想从字符串列表中删除一个变量(字符串)。所以基本上:

list = ["A", "G", "T", "C"]
number = 2
newlist = ["A", "G", "T", "C"] - list[number]
这应该是:

newlist = ["A", "G", "C"]
但当我尝试此操作时,它会显示以下错误消息:

Traceback (most recent call last):
  File "mini.py", line 3, in <module>
    newlist = ["A", "G", "T", "C"] - list[number]
TypeError: unsupported operand type(s) for -: 'list' and 'str'
回溯(最近一次呼叫最后一次):
文件“mini.py”,第3行,在
新列表=[“A”、“G”、“T”、“C”]-列表[编号]
TypeError:-:“list”和“str”的操作数类型不受支持
我该如何解决这个问题


提前谢谢

有几种方法可以做你想做的事

如果要修改起始列表(而不是创建新列表),可以使用
del
语句删除所需索引:

del oldlist[index]
如果您需要对要删除的值的引用(而且还没有),您可以在列表中调用
pop

value_removed = oldlist.pop(index)
如果希望保持旧列表的原样,则需要复制列表的数据,以便能够在不更改原始列表的情况下删除该值。一种方法是复制整个列表,然后在副本中的索引上使用
del

newlist = oldlist.copy() # or list(oldlist) or oldlist[:]
del newlist[index]
另一种选择是使用切片来获取索引之前的列表部分和索引之后的部分,然后将它们连接在一起。看起来是这样的:

newlist = oldlist[:index]
newlist.extend(oldlist[index + 1:])
您可以在一行中使用
+
操作符合并两个切片,但使用两行并调用
extend
可以避免不必要的第一个值切片的额外副本

请注意,除非
index
总是接近列表的末尾,否则所有这些方法都需要
O(len(oldlist))
时间才能完成,因此如果您关心性能,请不要在很长的列表中频繁执行此操作


在我的所有示例中,我都使用
oldlist
作为现有列表的名称。我强烈建议您避免在代码中使用
list
作为变量名,因为它会屏蔽内置的
list
类型。这通常不会立即成为问题(特别是如果函数中的
list
变量是局部变量),但如果您以后编辑代码并且不记得
list
在特定位置是局部变量,则可能会导致非常混乱的错误。

[“a”、“G”、“t”、“C”]。删除(list[number])
?或
列表.pop(编号)
。不清楚你为什么认为列表减法会奏效。另外,不要使用
list
作为您自己列表的标识符,它会隐藏内置的。
list
是Python中的保留字之一。最好不要将其用作变量名。