为什么这个简单的条件表达式不起作用?

时间:2015-10-05 17:32:35

标签: python conditional

很简单的一句话:

$locations = DB::table('businesses')
        ->select('id as business_id', 'name as business_name','area as business_area', 'address as business_address',
            'city as business_city', 'country as business_country','longitude as business_longitude',
            'latitude as latitude','postcode as business_postcode', 'category as business_category',
            'phone as business_phone','timing as business_timing', 'owner_id as business_owner_id',
            'latitude as business_latitude', 'longitude as business_longitude',('6371 * (acos( cos(radians
                    (' . $latitude . ') ) * cos( radians( `latitude` ) ) * cos( radians( `longitude` ) - radians(' . $longitude . ') ) + sin(
                        radians(' . $latitude . ') ) * sin( radians( `latitude` )) ) ) AS distance'))
        ->join('events', 'events.business_id', '=', 'businesses.id')
        ->select('events.id as event_id', 'events.title as event_title', 'type as event_type', 'event_type as event_event_type',
            'time as event_time', 'description as event_description', 'venue as event_venue','visibility as event_visibility',
            'picture as event_picture', 'max_people as event_max_people', 'admin_id as event_admin_id')
    ->get();

失败了:

i = 3
a = 2 if i in [1, 3, 6] else a = 7

然后扩展为:

SyntaxError: can't assign to conditional expression

工作正常。

2 个答案:

答案 0 :(得分:31)

你错了。以这种方式使用它:

a = 2 if i in [1, 3, 6] else 7

答案 1 :(得分:7)

应该是

 a = 2 if i in [1, 3, 6] else 7

您可以将其读作:

 a = (((2 if i in [1, 3, 6] else 7)))

也就是说,完全评估分配符号右侧的表达式,然后将结果分配给左侧。表达式本身是由条件分隔的两个值。