如何在python中检查数组中是否存在list元素

时间:2016-01-14 15:58:42

标签: python arrays 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输出

2 个答案:

答案 0 :(得分:3)

试试这个(来自Making a flat list out of list of lists in Python):

l = clusters_order_ids.values
out = [item for sublist in l for item in sublist]
print (bulk_order in out)

对于删除,您必须在每个列表中输入:

for sublist in clusters_order_ids.values:
    if bulk_order in sublist:
        sublist.remove(bulk_order)
        if not sublist:
            #do something to remove the empty list
        break;

答案 1 :(得分:3)

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

如果要删除列表['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']]