how to write if and else in a single line in python

Possible Duplicate:
Ternary conditional operator in Python

I am working on python and trying to save data in to database Suppose i had below code

conn = mdb.connect(user='root', passwd='redhat', db='Data', host='localhost', charset="utf8")

ex_li = ['stri_one','stri_two','stri_three','stri_four']

if ex_li[0] != '':
    campaignID = ex_li[0]
else:
    campaignID = ''

if ex_li[1] != '':
    keywordID = ex_li[1]
else:
    keywordID = ''
.........
.......

try:
    cursor = conn.cursor()
    query = "insert into PerformaceReport(campaignID, keywordID, keyword, avgPosition,cost)"
    query += "VALUES (%s, '%s', '%s', '%s')" %(campaignID, keywordID, keyword, avgPosition,cost)
    cursor.execute( query )
    conn.commit()
except Exception as e:
    print e,"!!!! Exception happend!!!!"

Here in the above code i am taking the strings from the list if they are not equal to empty string, because during slicing if there is no string it will display list index out of range error.

So is there any way to write these if and else statements in one line and submitting as value to query directly something like below(just given as an idea)

        query += "VALUES (%s, '%s', '%s', '%s')" %(if ex_li[0] != '': campaignID = ex_li[0]  else: campaignID = '' ............)

expression_if_true if condition else expression_if_false

所以试试

campaignID = main_res[0] if ex_li[0] != '' else ''

You can use the ternary expression (v2.5) from this SO answer. But instead I would recommend:

names = ['campaignID', 'keywordID' ... ]  
data = itertools.izip_longest(names, ex_li)
key_string = ','.join(data.keys())
query = '...(' + key_string + ')...( %s, %s, %s, %s )' #no % here
cursor.execute(query, data.values())

Explanation:

In answer to your modified question where you test ex_li[0] and then assign its value, there is no point in check for blank and assigning it if you find it, you can just do:

 campaignID = ex_li[0]

Then if ex_li[0] is '' , that's what you'll get in campaignID . You mention list index out of bounds , but that will not happen in the updated code unless your list is the wrong length.

But at a higher level you can remove these if statements entirely:

(campaignID, keywordID, ...) = ex_li

This is tuple unpacking. Alternatively build a dictionary, which seems more useful since you need to treat the IDs as both data and selector:

names = ['campaignID', 'keywordID' ... ]  
data = zip(names, ex_li)
# now have data = {'campaignID': ex_li[0], ... }

And you can construct your query appropriately:

query = 'insert into Performance report (' + ','.join(data.keys()) + ') ' +
        'values (' + ','.join("'"+elem+"'" for elem in data.values()) + ')'

A refinement might be that if you get None instead of an empty string (which will become 'None' as a string), then modify the value read for the zip:

data = zip(names, (elem or '' for elem in ex_li))

That should give you the empty string instead of 'None'.

If thg435 is right that you sometimes get a shorter list back, then you can zip in some extra '' :

data = zip(names, itertools.chain((elem or '' for elem in ex_li),
            itertools.repeat('')))

Here the repeat will give an endless list of '' , and the chain will take elements from ex_li until it runs out, then start getting '' from the repeat . zip runs until one or other iterator runs out, so it will stop when names is exhausted. Alternatively, if you'd rather handle the None values separately, you can izip_longest :

data = itertools.izip_longest(names, ex_li)
key_string = ','.join(data.keys())
value_string = ','.join("'"+str+"'" for str in 
    (elem or '' for elem in data.values()))
query = '...(' + key_string + ')....(' + value_string + ')...'

or to ease readability:

def quotify(str):
    return "'"+str+"'"

However, don't do that. Use cursor.execute in the DB API rather than quoting values yourself, as many SO questions attest (eg Python: get escaped SQL string):

query = '...(' + key_string + ')...( %s, %s, %s, %s )' #no % here
cursor.execute(query, data.values())

This allows the DB API to do the escaping correctly for you, preventing injection attacks or accidents.


你可以尝试如下所示:

value_when_true if condition else value_when_false
链接地址: http://www.djcxy.com/p/7404.html

上一篇: Python布尔真理测试

下一篇: 如何写python中的if和else