-1

I am trying to find out the result shown below with list comprehension:

def X(numbers):
    result = []
    for i in numbers:
        if i > 5:
            result.append('higher')
        else:
            result.append('lower')
        
    return result

numbers=[8,3,7]
assignment_02a(numbers)

Answer:['higher', 'lower', 'higher']

I have tried this code:

[i>5 for i in range(4,8) ]

I got this: [False, False, True, True]

I expect output to be: ['lower', 'lower', 'higher', 'higher']

Erog
  • 9
  • 1
  • 1
  • 7
  • 1
    Next time please do a little research in SO, there are tons of examples with list comprehension, I`m sure you could come up with your own solution... [Link1](https://stackoverflow.com/questions/2951701/is-it-possible-to-use-else-in-a-list-comprehension) [Link2](https://stackoverflow.com/questions/4260280/if-else-in-a-list-comprehension) – Mouse on the Keys Oct 28 '19 at 22:09

3 Answers3

2

Refer to Link there you can find solution for this problem if you read it, carefully.

number = [8,3,7]
numbers = ["Higher" if i>=5 else "Lower" for i in number]
print(numbers)

Output:['Higher', 'Lower', 'Higher']

Or with range as you asked:

numbers = ["Higher" if i>5 else "Lower" for i in range(4,8)]
print(numbers)

Output: ['Lower', 'Lower', 'Higher', 'Higher']

Community
  • 1
  • 1
Mouse on the Keys
  • 322
  • 1
  • 5
  • 13
1

Well, your list comp function is only doing a test for higher/lower but not substituting the result. You could do this in a number of ways but in keeping with the spirit of things you could deference the string from a map.

[{True: "Higher", False: "Lower"}[i>5] for i in range(4,8)]

you could use a map function with a lambda to get fancy but this should illustrate the idea.

Will
  • 1,532
  • 10
  • 22
0
[{True:'higher', Talse:'lower'}[i>5] for i in range(4,8)]

if you're getting True or False then simply use those values with a dictionary. this means that:

  • If i > 5 then look in the dict and find that True returns 'higher'
  • If i < 5 then look in the dict and find that False returns 'lower'

[i>5 for i in range(4,8) ] returns whether or not i > 5. If we use a dict then True relates to 'higher' so we return it and False relates to 'lower' so we return that.

Xander Bielby
  • 161
  • 1
  • 12