Skip to main content
 首页 » 编程设计

python之如何检查列表元素是否存在于python中的数组中

2025年05月04日17shihaiming

我有一个 list

bulk_order 
Out[230]:  
[3    523 
Name: order_id, dtype: object] 

我有一个数组。它是一个系列,但我正在使用 values

访问它
clusters_order_ids.values 
Out[231]:  
array([['520', '521', '524', '527', '532'], ['528'], ['531'], 
   ['525', '526', '533'], ['519', '523', '529', '534', '535'], ['530']],      
dtype=object) 

现在我想检查 list element 523 是否存在于上面的数组中,如果存在我想删除它。

我正在用 python 进行跟踪

bulk_order in clusters_order_ids.values 

但它给了我 False 输出

请您参考如下方法:

您的列表不是列表,而是列表的列表。

如果你想删除包含列表 ['523'] 中的内容的整个列表:

orders = [['520', '521', '524', '527', '532'], ['528'], ['531'], ['525', '526', '533'], ['519', '523', '529', '534', '535'], ['530']] 
remove_order_with_ids = ['523'] # or bulk_order  
orders = [order for order in orders if not set(remove_order_with_ids).intersection(set(order))] 
print orders 
# [['520', '521', '524', '527', '532'], ['528'], ['531'], ['525', '526', '533'], ['530']] 

如果您只想从内部列表中删除 ['523'] 中的项目:

orders = [['520', '521', '524', '527', '532'], ['528'], ['531'], ['525', '526', '533'], ['519', '523', '529', '534', '535'], ['530']] 
remove_order_with_id = ['523'] # or bulk_order  
new_orders = [] 
for order in orders: 
    new_orders.append([item for item in order if item not in remove_order_with_id]) 
print new_orders 
# [['520', '521', '524', '527', '532'], ['528'], ['531'], ['525', '526', '533'], ['519', '529', '534', '535'], ['530']]