Discuss / Python / 奇怪的想法。。 还有问题

奇怪的想法。。 还有问题

Topic source

Orionial

#1 Created at ... [Delete] [Delete and Lock User]
# -*- coding: utf-8 -*-

L1 = ['Hello', 'World', 18, 'Apple', None]

for key in L1:
    if isinstance(key,str):
      pass
    else:
      L1.pop(key)

我的思维还真是与众不同又好累赘呵呵呵呵。。。但是我这样写会报错说pop越界?应该怎么解决

_周思思_

#2 Created at ... [Delete] [Delete and Lock User]

pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值

商郡马

#3 Created at ... [Delete] [Delete and Lock User]

没有要求删除L1中不是字符串的元素

在此插入代码

L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [] for key in L1: if isinstance(key,str): L2.append(key)

Morvin_Z

#4 Created at ... [Delete] [Delete and Lock User]

因为pop方法所使用的索引i是整形数字,你这个key正好是18,相当于要删除第19个元素,所以pop越界

如果增加一个i变量,表明是第3个元素,那么就可以正常删除了。 一楼说的不对,.pop(i)可以删除list第i+1个元素。

在此插入代码

L1 = ['Hello', 'World', 18, 'Apple', None]
i=0;
for key in L1:
    if isinstance(key,str):
      pass
    else:
      L1.pop(i)
    i+=1
print (L1)

  • 1

Reply