I want a function that takes a list and returns that list with any elements less than 0 or greater than "upper" removed.
I figured out how to do it with a list comprehension, but I can't figure out why this didn't work:
dim = 4
def ensure_values(l, upper=dim**2):
for i in l:
if i < 0 or i >= upper:
l.remove(i)
return l
l = [0,2,-3,5]
ensure_values(l)
[0,2,-3,5]
I expected [0,2,5].
Best practice in Python would be for your function to return a new list that contains only the desired elements. This is best done with a list comprehension.
dim = 4
def ensure_values(lst, upper=dim**2):
return [n for n in lst if 0 < n <= upper]
lst = [0,2,-3,5]
assert ensure_values(lst) == [2, 5]
Note that I was able to use the expression 0 < n <= upper
. That's not legal in C or most other languages, but in Python it is legal and does what one would expect it to do.
Also, I recommend against using l
as a variable name. It looks almost exactly like a 1
or an I
in many fonts. Recommended practice is to use lst
or L
for a short name for a list.
The use of l
as a variable name is specifically dis-recommended in the PEP 8 coding style guidelines for Python. Here's a link:
You could hange your loop so it iterates over a copy of the list, which avoids modifying the list you're iterating over, because that won't work in many cases.
dim = 4
def ensure_values(l, upper=dim**2):
for i in l[:]: # iterate over copy of list
if i < 0 or i >= upper:
l.remove(i)
return l
l = [0, 2, -3, 20, 5]
print ensure_values(l) # -> [0, 2, 5]
A more "Pythonic" way to do it — because it's shorter and doesn't need a copy of the list — would be to use a list comprehension. Note the condition had to be reversed because it's now being used to determine when to keep elements.
l = [i for i in l if i >= 0 and i < dim**2]
print l # -> [0, 2, 5]
Why not use a filter?
def ensure_values(l, upper=dim**2):
return filter(lambda x: x>0 or x<upper, l)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.