Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's a lot of answers here :)</p> <p>The two best answers (performance and clean code in one line) are the answers of @icecrime and @Hoopdady</p> <p>Both asnwers results equally, the only difference is performance.</p> <pre><code>cases = [ (None, 'testB'), ('', 'testB'), ('testA', 'testB'), ('testA', ''), ('testA', None), (None, None) ] for case in cases: print '-'.join(filter(bool, case)) 'testB' 'testB' 'testA-testB' 'testA' 'testA' for case in cases: print '-'.join([x for x in case if x]) 'testB' 'testB' 'testA-testB' 'testA' 'testA' </code></pre> <p>So let's do a benchmark :)</p> <pre><code>import timeit setup = ''' cases = [ (None, "testB"), ("", "testB"), ("testA","testB"), ("testA", ""), ("testA", None), (None, None) ] ''' print min(timeit.Timer( "for case in cases: '-'.join([x for x in case if x])", setup=setup ).repeat(5, 1000)) 0.00171494483948 print min(timeit.Timer( "for case in cases: '-'.join(filter(bool, case))", setup=setup ).repeat(5, 1000)) 0.00283288955688 </code></pre> <p>But, as @mgilson said, using <code>None</code> instead of <code>bool</code> as the function in <code>filter</code> produces the same result and have a quite better performance:</p> <pre><code>print min(timeit.Timer( "for case in cases: '-'.join(filter(None, case))", setup=setup ).repeat(5, 1000)) 0.00154685974121 </code></pre> <p>So, the best result is the answer gave by @icecrime with the suggestion from @mgilson:</p> <pre><code>'-'.join(filter(None, (a,b))) </code></pre> <p>The performance difference is in milliseconds per 1000 iterations (microseconds per iteration). So these two methods have a quite equals performance, and, for almost any project you could choose any one; In case your project must have a better performance, considering microseconds, you could follow this benchmark :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload