2

I´m trying to implement generator notation into my code, specifically into my str() method. This is what I have so far and now I need to add "elif" statement there, but not sure how to type it into this generator notation. Can you help?

def __str__(self):
    lines = []
    for sub_list in self.tab:
        lines.append(' '.join([str(item) for item in sub_list if not isinstance(item, set) else '.']))
    return '\n'.join(lines)
fin1010
  • 69
  • 1
  • 5
  • 1
    You can't. is the 'else' even valid? Just don't do it in a one-liner – Hagai Wild Dec 23 '18 at 11:48
  • What is the typical input, and what is the expected output, and what might your `elif` condition be? As it is the question is missing a lot of vital details which isn't likely to produce an answer you want (and people who have answered already might possibly got some wrong assumptions). – metatoaster Dec 23 '18 at 11:54

2 Answers2

2

You had the order wrong:

def __str__(self):
    lines = []
    for sub_list in self.tab:
        lines.append(' '.join([str(item) if not isinstance(item, set) else '.' for item in sub_list ]))
    return '\n'.join(lines)

The general structure of your list comprehension is

[somefunction(item) for item in sublist].

Using if as you did:

[somefunction(item) for item in sublist if <some_condition on item>]

means that you only include somefunction(item) if some_condition is satisfied. There can't be any elif here, as there is only one choice: include in the resulting list or not.

You want to generate an output for each of your items, so you don't need an if clause like that. But somefunction(item) can be the result of the evaluation of the ternary operator str(item) if not isinstance(item, set) else '.'.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
  • Might be worth it to explain that what the OP had filters the elements of the iterable, while this uses a ternary expression as the value. – Graipher Dec 23 '18 at 11:53
  • 1
    but that's still a ternary operator, the OP asked for an 'elif' in it. – Hagai Wild Dec 23 '18 at 11:53
0

if else constructs go before for item in sub_list in a list comprehension.

sub_list = [{1}, [1], {2, 3}]

lines = []
lines.append(' '.join([str(item) if not isinstance(item, set) else '.' for item in sub_list ]))
print(lines) #Output: ['. [1] .']

Adding an elif can be done by chaining the conditional expressions, though there is no elif keyword directly supported in conditional expressions. Example:

sub_list = [{1}, [1], {2, 3}]
lines = []
lines.append(' '.join([str(item) if not isinstance(item, set) else '.' if len(item) == 1 else '!' for item in sub_list ]))
#similar to elif '.' if len(item) == 1 else '!'
print(lines) #Output: ['. [1] !']
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33