So i am working on this function that takes a list as a parameter containing positive int, negative int, and the number 0 (zero). I have written the function using a while function with nested if statements to determine the value of each integer. Here is an example:
def Signs1(numList):
num = 0
while num < len(numList):
if numList[num] > 0:
print('p')
elif numList[num] == 0:
print('z')
else:
print('n')
num = 1
My question is how do i return each print statement in a List order, like so: ['p', 'p', 'p', 'n', 'z', 'n']
I have tried including the (end=" ") function to return them all on one line which works fine but i want to return them using a return function. Is this possible and if so how would one go about to do this?
CodePudding user response:
You could use a list comprehension like this:
def Signs(alist):
return ['z' if n == 0 else 'p' if n > 0 else 'n' for n in alist]
print(Signs([-1,0,1]))
Output:
['n', 'z', 'p']
CodePudding user response:
With while loop, initialize an empty list (res
), use its length as counter in while
loop. Check element of numlist
using length of res
as index, append it to res
, and return res
:
def Signs1(numList):
res = []
while len(res) < len(numList):
if numList[len(res)] > 0:
res.append('p')
elif numList[len(res)] == 0:
res.append('z')
else:
res.append('n')
return res
numlist = [2,6,-1,3,0,-4,1,5]
result = Signs1(numlist)
print(result)
# ['p', 'p', 'n', 'p', 'z', 'n', 'p', 'p']
CodePudding user response:
Instead of printing this you can modify the list or use another one:
def Signs1(numList):
num = 0
output_list = []
while num < len(numList):
if numList[num] > 0:
output_list.append('p')
elif numList[num] == 0:
output_list.append('z')
else:
output_list.append('n')
num = 1
return output_list