从列表[重复]中删除项目时的奇怪结果我有一段代码:numbers = range(1, 50)for i in numbers:
if i < 20:
numbers.remove(i)print(numbers)但我得到的结果是:[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]当然,我期望20以下的数字不会出现在结果中,我假设我做了一些错误的删除。
4 回答
喵喵时光机
TA贡献1846条经验 获得超7个赞
[1,2,3,4,5............50] ^[2,3,4,5............50] ^[3,4,5............50] ^
aList = range(50)i = 0while i < 20: aList.pop(0) i += 1print aList #[21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
lis = range(50)lis = lis[20:]
functional = filter(lambda x: x> 20, range(50))
catspeake
TA贡献1111条经验 获得超0个赞
li = range(1,15)print li,'\n'for i in xrange(len(li)-1,-1,-1): if li[i] < 6: del li[i]print li
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] [6, 7, 8, 9, 10, 11, 12, 13, 14]
炎炎设计
TA贡献1808条经验 获得超4个赞
我唯一想添加的东西(我本可以注释,但无法获得适当的代码格式)是,如果您提前声明了如下函数,那么您也可以为您的列表理解进行边处理:
def checkRemoval(item): # some processing here return passed_inspection # Should be True / False.newList = [item for item in oldList if checkRemoval(item)]
添加回答
举报
0/150
提交
取消