Domanda

Si prega, spostare questa domanda a Code Review -Area . E 'più adatto lì perché so che il codice qui sotto è spazzatura e ho voluto un feedback fondamentale per completa riscrittura.

Come faccio a scrivere i rapporti set-to-costanti in Python? Quindi, se A in un intervallo, per poi tornare la sua costante corrispondente.

[0,10]    <-> a
]10,77]   <-> b
]77,\inf[ <-> c

Codice Annusare, male.

    # Bad style

    provSum=0


    # TRIAL 1: messy if-clauses
    for sold in getSelling():
            if (sold >=0 & sold <7700):
                    rate =0.1 
            else if (sold>=7700 & sold <7700):   
            #won't even correct mistakes here because it shows how not to do things
                    rate =0.15
            else if (sold>=7700):
                    rate =0.20


    # TRIAL 2: messy, broke it because it is getting too hard to read
    provisions= {"0|2000":0.1, "2000|7700":0.15, "7700|99999999999999":0.20}


    if int(sold) >= int(border.split("|")[0]) & int(sold) < int(border.split("|")[1]):
            print sold, rate
            provSum = provSum + sold*rate
È stato utile?

Soluzione

Se la lista fosse più lungo di soli tre voci, vorrei utilizzare bisect.bisect():

limits = [0, 2000, 7700]
rates = [0.1, 0.15, 0.2]
index = bisect.bisect(limits, sold) - 1
if index >= 0:
    rate = rates[index]
else:
    # sold is negative

Ma questo sembra un po 'overengineered solo per tre valori ...

Modifica: Il secondo pensiero, la variante più leggibile probabilmente è

if sold >= 7700:
    rate = 0.2
elif sold >= 2000:
    rate = 0.15
elif sold >= 0:
    rate = 0.1
else:
    # sold is negative

Altri suggerimenti

if (sold >=0 & sold <7700):

è equivalente a

if 0 <= sold < 7700:

io non sono a conoscenza di un veramente ottimo modo per map gamme, ma questo lo rende molto più estetico almeno.

Si potrebbe utilizzare il secondo approccio troppo:

provisions = {(0, 2000) : 0.1, (2000,7700):0.15, (7700, float("inf")):0.20}

# loop though the items and find the first that's in range
for (lower, upper), rate in provisions.iteritems():
    if lower <= sold < upper:
        break # `rate` remains set after the loop ..

# which pretty similar (see comments) to
rate = next(rate for (lower, upper), rate in 
                 provisions.iteritems() if lower <= sold < upper)    
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top