I want to make a code that receives a random list and stores only positive numbers. However, if I run it with the code I wrote, I only get positive numbers, but the order is reversed. What should I do?
As an example of the code, [3, 2, 1, 0] is displayed. I want to print this out [0, 1, 2, 3].
def filter(list):
flist = []
for i in list:
if list[i]>=0:
flist.append(list[i])
else:
continue
return flist
list = [-1,-2,-3,-4,0,1,2,3]
print(filter(list))
CodePudding user response:
sort before returning the list
def filter(list):
flist = []
for i in list:
if list[i]>=0:
flist.append(list[i])
else:
continue
flist.sort()
return flist
list = [-1,-2,-3,-4,0,1,2,3]
print(filter(list))
Output:
[0, 1, 2, 3]
CodePudding user response:
Try:
print(filter(list[::-1]))
CodePudding user response:
for i in list
iterates over the items in the list, not the indices. Since the first four items in the list are negative numbers, when you use them as indices, you end up iterating through the last half of the list in reverse order before reaching zero and then iterating through the first half of the list in forward order. (If all the items in the list didn't happen to be valid indices for that same list, you'd just get an IndexError
instead.)
To iterate over all the items in the list in order by index use range
and len
:
# 'filter' and 'list' are both builtin names, don't redefine them
def filter_nat(nums):
flist = []
for i in range(len(nums)):
if nums[i]>=0:
flist.append(nums[i])
else:
continue
return flist
nums = [-1,-2,-3,-4,0,1,2,3]
print(filter_nat(nums)) # [0, 1, 2, 3]
It's simpler to iterate by value, though; you just need to use the value itself rather than trying to use it as an index:
def filter_nat(nums):
flist = []
for i in nums:
if i >=0:
flist.append(i)
return flist
nums = [-1,-2,-3,-4,0,1,2,3]
print(filter_nat(nums)) # [0, 1, 2, 3]
and it's simpler yet to use a comprehension instead of individually append
ing each item:
def filter_nat(nums):
return [i for i in nums if i >= 0]
nums = [-1,-2,-3,-4,0,1,2,3]
print(filter_nat(nums)) # [0, 1, 2, 3]
CodePudding user response:
What do you want? Something in the same order as encountered reading from left to right or in increasing order? If it is in the order of reading in initial list, here is the answer:
function append() adds the element at the end of the list. Hence, you could either go over the list from the end to its beginning using append() or going in same order as you, use another fashion in order to add the element at the beginning. When sticking to your code, we would have
def filter(list):
flist = []
for i in list:
if list[i]>=0:
flist = [i] flist
else:
continue
return flist
However, this could be written way more "pythonic" in the following way:
def filter(list):
return [i for i in list if i>=0]
CodePudding user response:
Try for i in range (len(list)):
You would be looping through the number of items in the list. Personally it is easier and cleaner code for me but everyone has his preferences.