简化列表中的条件

时间:2017-04-22 07:58:24

标签: python python-2.7 list if-statement

以下代码需要三行。是否可以简化为一行?

code = [x for x in code if not 'W' in x]
code = [x for x in code if not '06501' in x]
code = [x for x in code if not '06502' in x]

我正在尝试这个,但没有工作

code = [x for x in code if not 'W' or if not '06501' or if not '06502' in x]

3 个答案:

答案 0 :(得分:2)

你最好能做到这一点:

remove_item = ['w', '06501', '06502']
code = [x for x in code if x not in remove_item]

答案 1 :(得分:1)

这是一种方法

[ x for x in code if not any( i in x for i in ['W', '06501', '06502'])]

备用版本

[ x for x in code if not any(map(lambda i: i in x, remove_items)) ]

修改相同以使用过滤器

filter(lambda x: not any(map(lambda i: i in x, remove_items)), code)

注意:选择使用哪种语义主要是个人偏好。但是最后一个版本可能更好code很大,因为它返回一个生成器对象进行延迟评估(在python3中)

答案 2 :(得分:0)

这应该有效。

// You can use a setInterval also, but im using button click to call api
$(document).on('click', '.button', function(event) {
    	event.preventDefault();
    	var url1 = BASE_URL+"controller/method"; // Or your API
    	$.ajax({
    		url: url1,
    		type: 'GET',
    		dataType: 'json',
    		success : function(response){
           // Access the json objects like this
           // eg. response.status, response.data etc.
           
           // Do DOM manipulation
           // eg. $('#target').text(response.data) 
    		},
    		failure : function(response){
    			alert("Error! Please Contact technical support");
    		}
    	});

    });

这适用于以下输入:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

你也可以像这样使用数组:

code = [x for x in code if not ('W' in x or '06501' in x or '06502' in x)]