我的目标是使用列表理解来返回列表中的值.具体来说,如果列表中有'x'
,我想删除所有其他值.但是,如果列表中没有'x'
,我想返回相同的值(而不是返回空列表).
list1 = ['d','x','c']
list2 = ['d','b','c']
list1 = [s for s in list1 if s == 'x']
list2 = [s for s in list2 if s == 'x']
列表2将返回[]
.我想要的地方['d','b','c']
list2 = [s for s in list2 if s == 'x' else list2]
退货:
list2 = [s for s in list2 if s == 'x' else list2]
^^^^
SyntaxError: invalid syntax