首页 > python > 如何删除python列表理解中的代码双重性?

如何删除python列表理解中的代码双重性? (How to remove code duplicity in python list comprehension?)

问题

如何通过组合成一个列表解析来解决以下代码的两面性?

 myList   =[ //someList      ]      
 thierList=[ //someOtherList ]      

 if name:
          [x for x in range(2,100) if x%2 and x in mylist and x not in theirList]

 else:
          [x for x in range(2,100) if x in mylist and x not in theirList] 

解决方法

[x for x in range(2,100) if x in mylist and x not in theirList if not name or x%2 ]

问题

How to resolve the following code duplicity by combining into one list comprehension?

 myList   =[ //someList      ]      
 thierList=[ //someOtherList ]      

 if name:
          [x for x in range(2,100) if x%2 and x in mylist and x not in theirList]

 else:
          [x for x in range(2,100) if x in mylist and x not in theirList] 

解决方法

[x for x in range(2,100) if x in mylist and x not in theirList if not name or x%2 ]
相似信息