How do I evaluate multiple variables with one if statement

时间:2019-04-16 23:03:29

标签: python python-3.x

I am currently storing values provided by an API response that returns XML, certain nodes come back with 'false' or 'true' I am capturing these values as a string type.

XML Code:

<hidden>false</hidden>
<ssl>true</ssl>
<current_payout>true</current_payout>

I want to parse through these values and if I find a match I would like to change 'true' to 'on' and false to 'off' depending on the variable that matches.

I am only able to accomplish this with one variable, my goal is to clean up my code and find a more efficient way, any advice is appreciated.

Here is my block of code:

import requests
import json
import csv
from bs4 import BeautifulSoup



for data in csv_reader:

req = requests.get(url, params=params)
response = BeautifulSoup(req.text, 'lxml')

hidden = response.find('hidden').string
ssl = response.find('ssl').string
currentPayout = response.find('current_payout').string

if hidden == 'true':
    hidden = 'on'
if hidden 'false':
    hidden = 'off'

if ssl == 'true':
    ssl = 'on'
if ssl = 'false':
    ssl = 'off'

if currentPayout == 'true':
    currentPayout = 'on'
if currentPayout = 'false':
    currentPayout = 'off'

Question: How do I take my 3 if statements and consolidate my code?

2 个答案:

答案 0 :(得分:2)

How about this:

response_map = {'true': 'on', 'false': 'off'}
find_terms = {'hidden', 'ssl', 'current_payout'}

result = {find_term: response_map[response.find(find_term)] for find_term in find_terms}

result['hidden'], result['ssl'] and result['current_payout'] will have the values you want.

答案 1 :(得分:1)

gmds has a good answer, however if you want to keep your code out of a loop you could use ternary assignment to streamline your existing code a bit.

ssl = 'on' if ssl == 'true' else 'off'
hidden = 'on' if hidden == 'true' else 'off'
currentPayout = 'on' if currentPayout == 'true' else 'off'