Logic test inside the Python array

Asked

Viewed 225 times

-2

In the R I can have this structure

var1 <-TRUE
var2 <-FALSE
paste0("ANO_544, SEMANA",
      if(var1 == TRUE){", COD_NEGOCIO"},
      if(var2 == TRUE){", CATEGORIA"},
      ", MODULADO")

And I got an answer:

"ANO_544, SEMANA, COD_NEGOCIO, MODULADO"

This is useful for making SQL requests, such as:

library(DBI)
var1 <-TRUE
var2 <-FALSE
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars)

var1 <-FALSE
var2 <-TRUE
dbGetQuery(con, paste0("SELECT
                  disp,",
                       if(var1 == TRUE){"gear,"},
                       if(var2 == TRUE){"carb,"},
                       "avg(qsec)
                FROM mtcars
                  group by
                  disp",
                       if(var1 == TRUE){",gear"},
                       if(var2 == TRUE){",carb"}))
dbDisconnect(con)

So I can change the query by changing the values of var1 and var1.

The question: Is there a structure like this in Python? I can do it inside the pd.read_sql(" ".join([...]), cursor) ?

  • Explain your problem better, I don’t understand what you want to do and what kind of logical operation to run over the array. Where’s your Python code? Put it to make it easy.

  • It is not very clear what you want to do. Do you want the return to be an array? And based on conditionals it contains or not certain elements?

2 answers

1


It is not possible, because if the condition is not satisfied, what would be the value returned? There needs to be a return. But if there is a second value if the condition is not met, it can be in several ways:

print(', '.join([
    'A',
    'B' if True else 'b',
    ('C', 'c')[False],
    'd' == 'D' or 'D',
    'e' != 'E' and 'E',
    False and 'f' or 'F'
]))

I think (I’m not sure) that these are all possible forms of a "ternary"

There is no way to add to the list stored in a variable:

lista = ['A']
if True: lista.append('B')

Or use a specific value if the condition is not satisfied and then filter the list by removing the occurrences of that value:

l = ['A', 'B' if False else None]
l.remove(None)

Depending on the case, as a string concatenation, just use a value that will not change the final result (for example, an empty string ''):

l = ['A', 'B' if False else '', 'C']
print(''.join(l)) //AC
  • Then I can return ' ' (emptiness)?

  • It can, but it’s not like there isn’t a value. In your case it might work, but it won’t work at all

1

You could create the list with all fields and filter the result later.

The module itertools has the function itertools.compress that "removes" the elements of an iterable based on the boolean value of another iterable.

Example:

from itertools import compress

var1, var2 = True, False
lista = ["ANO_544", "SEMANA", "COD_NEGOCIO", "CATEGORIA", "MODULADO"]
filtros = [True, True, var1, var2, True]

resultado = ", ".join(compress(lista, filtros))

print(resultado)

See rotating on Repl.it

Whatever True will be included in the result and whatever False nay.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.