因此,如果我没看错,您需要删除列表中所有索引为质数的项目。如果是这样,你想要这个:
def deletePrimeIndex(l):
return [value for index, value in enumerate(l) if index > 1 and not all(index % i for i in range(2, index))]
如果您希望该值不是素数:
def deletePrimeValue(l):
return [value for value in l if value > 1 and not all(value % i for i in range(2, value))]
输出:
In [1]: print deletePrimeIndex(range(1, 50))
Out [1]: [5, 7, 9, 10, 11, 13, 15, 16, 17, 19, 21, 22, 23, 25, 26, 27, 28, 29, 31, 33, 34, 35, 36, 37, 39, 40, 41, 43, 45, 46, 47, 49]
In [2]: print deletePrimeValues(range(1, 50))
Out [2]: [4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 22, 24, 25, 26, 27, 28, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 44, 45, 46, 48, 49]
注意:当您使用range(1, 50)
每个值时,都会比它的索引大一位。IE :range(1, 50)[0]
不会1
。0
此外,从技术上讲,这两者都确实返回了新列表。