-1

I am trying to un condense:

samp_neighs = [_set(_sample(to_neigh, 
                            num_sample,
                            )) if len(to_neigh) >= num_sample else to_neigh for to_neigh in to_neighs]

into multiple lines. Can someone help? Thank you in advance!

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Gillerm
  • 9
  • 1
  • Are you asking for an automatic formatting tool? – bnaecker Sep 03 '20 at 19:32
  • 1
    Show us what you tried, and which specific problem you hit when doing it yourself. In general, we don't write or translate code for you, _or_ explain code that's provided unless given a very specific description of which aspect of that code requires explanation; that can include building a [mre] that factors out all the aspects of the code that you _do_ already understand, and which thus don't require explanation. – Charles Duffy Sep 03 '20 at 19:32
  • Check out this answer: https://stackoverflow.com/a/59128169/1456253 – code11 Sep 03 '20 at 19:32

2 Answers2

2

If I wrote out your code in a few lines rather than a single line it would look something like this:

result = []

for to_neigh in to_neighs:
    if len(to_neigh) >= num_sample:
        result.append(_set(_sample(to_neigh, num_sample)))
    else:
        result.append(to_neigh)
spyralab
  • 161
  • 6
0

If the goal is simply improve readability (since there is no other benefit of writing a for loop), you can extract _set(...) if .. else .. to its own function rather than shove it into a list comprehension

For example

def foo(to_neigh, num_sample):
    s = _sample(to_neigh, num_sample,)
    return _set(s) if len(to_neigh) >= num_sample else to_neigh

Then you can map that function over the list

num_sample = ...
samp_neighs = list(map(lambda n: foo(n, num_sample), to_neighs))
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 1
    I like your answer. It's not exactly what OP asked for but I think it's elegant if it needs to be reused. To answer the question specifically you could "uncondense" the return statement in foo – spyralab Sep 03 '20 at 19:42