IF语句压缩多个OR语句

时间:2018-09-26 21:24:41

标签: python if-statement

我有以下一行

if 'smoke' in row['product'].lower() or 'grill' in row['product'].lower() or 'choco' in row['product'].lower(): 

我想在OR子句中添加多个项目。 ['smoke','grill,'choco',...],如何在不失去逻辑的情况下精简if语句?

2 个答案:

答案 0 :(得分:3)

您可以将生成器表达式与@SpringBootConfiguration @Import(value = { BaseConfig.class }) class App { public static void main(String[] args) { SpringApplicationBuilder app = new SpringApplicationBuilder(App.class); app.child(ConfigA.class).run(args); app.child(ConfigB.class).run(args); } } 一起使用:

#Check process list for dead processes
def clean_process_list(self):
    logger.info("Checking for dead or orphaned processes.")
    if len(self.processes):
        for i in range(0, len(self.processes)):
            process = self.processes.pop()
            if process.is_alive() is not True:
                logger.info("{} is unresponsive; terminating process.".format(process.name))
                process.terminate()
            else:
                self.processes.appendleft(process)

#Worker method which puts results from a target method into a queue, if any exist. Self-terminates on completion.
def worker(self, args):
    worker_name = multiprocessing.current_process().name
    logging_socket = tcp_log_socket.local_logging_socket('test.json', worker_name) #reinitializing logger in worker for troubleshooting
    logger = logging_socket.logger
    logger.info("Running process {}; waiting for results.".format(worker_name))
    results = self.target_method(*args)
    results_queue = self.process_results
    logger.info("Ran target method, storing results and name of finished process.")
    results_queue.put([results, worker_name])
    logger.info("Process {} completed, exiting.".format(worker_name))
    sys.exit(0)

#Creates and uses a process to run a job using the assigned target method. 
def use_process(self, args):
    self.clean_process_list()
    self.process_results = multiprocessing.Queue()
    process = multiprocessing.Process(target=self.worker, args=(args,))
    logger.info("Created process; process name is {}".format(process.name))
    self.processes.append(process)
    process.start()
    logger.info("Process {} started.".format(process.name))

答案 1 :(得分:0)

一种方法是使用any

if any(item in row['product'].lower()
       for item in ('choco', 'smoke', 'grill'):

或者如果row['product'].lower()是一个字符串,并且您想比较它们是否相同:

if row['product'].lower() in ('choco', 'grill', 'smoke'):

在具有名称元组的地方,将其替换为预先编写的字符串列表,如下所示:

names = ('choco', 'grill', 'smoke', ...)
if row['product'].lower() in names: