gpt4 book ai didi

python - 从列表中删除整数+python

转载 作者:行者123 更新时间:2023-12-01 03:00:14 24 4
gpt4 key购买 nike

下面是我想要分隔字符串和整数的列表。

这个列表给了我正确的结果:

list_a = ["Michell",123,"Apple","Food",456,"Another"]
list_e = []
x = 0

for item in list_a:
print("x is: ", x)
print("item is: ", item)
if isinstance(item,int):
list_e.append(item)
list_a.pop(x)

x+=1
print(list_a)
print(list_e)

当我向列表中添加一个元素时,问题就开始了,如下所示:在 456 之后添加了元素 3231...

>>> list_a = ["Michell",123,"Apple","Food",456,3231,"Another"]
...
['Michell', 'Apple', 'Food', 3231, 'Another']
[123, 456]

这里有什么问题吗?

最佳答案

问题是:

  1. 当您从列表中删除项目时,您正在迭代该列表,并且
  2. 您的计数器变量x没有考虑已删除项目的位置。

试试这个:

list_a = ["Michell",123,"Apple","Food",456,3231,"Another"]
list_e = []
x = 0

for item in list_a[:]:
print "x is: ", x
print "item is: ", item, type(item)
if isinstance(item,int):
list_e.append(item)
list_a.pop(list_a.index(item))

x+=1
print list_a
print list_e

另请参阅:

(1) , (2) , (3)

关于python - 从列表中删除整数+python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43919477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com