在python中过滤字符和数字混合数据的最有效方法

2024-05-19 21:13:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有标题(ID、process、material、finish)的订单列表和一个机器数据集。它有标题(ID、process、materials、finishes)。对于每一个订单,我想找到兼容的机器。你知道吗

我可以创建一个包含订单的列表和一个包含机器的列表,并使用for循环来完成这个任务。代码如下所述。然而,我想要一个更有效的方法来做同样的事情。你知道吗

orders = [[1, 'cutting', 'Al', 200], [2, 'boring', 'Al', 200]]

machines = [[1, 'cutting', ['Steel', 'Al'], [100,200,300]], \
            [2, 'boring', ['titanium', 'PLA', 'ABS'], [100,200]], \
            [3, 'hobbing', ['wood', 'Al', 'SS'], [300,400]]]

match = []
for i in range(len(orders)):
    for j in range(len(machines)):
        if orders[i][1] == machines[j][1] and orders[i][2] in machines[j][2] and \
        orders[i][3] in machines[j][3]:
           match.append([orders[i][0], machines[j][0]])   

print (match)

我不能使用numpy数组,因为机器中的material和resolution列由长度不同的列表组成,列表不能是numpy数组中的元素。请给出一个更有效的方法。我有成百上千的订单和机器,所以这种for-loop方法变得非常低效。你知道吗


Tags: 方法in订单机器id标题列表for
1条回答
网友
1楼 · 发布于 2024-05-19 21:13:33

首先,我们可以用以下方法清理迭代:

for order in orders:
    for machine in machines:
        if order[1] == machine[1] and order[2] in machine[2] and \
        order[3] in machine[3]:
           match.append([order[0], machine[0]])   

它可能在速度上没有太大的差别,但确实使事情更具可读性。你知道吗

for order in orders:
    for machine in machines:
        if order[1] == machine[1] and \ 
           order[2] in machine[2] and \
           order[3] in machine[3]:
           match.append([order[0], machine[0]]) 

如果machinesmachine[1]上是唯一的,那么制作字典可能会有所帮助

machine_dict = {machine[1]: [machine[0], machine[2], machine[3]] for machine in machines}

在循环中:

for order ...
    machine = machine_dict[order[1]]
    # but what if there's a keyerror?
    # the rest of the test

如果有多台机器具有相同的[1],那么字典将更加复杂,但可能仍然有用。你知道吗

相关问题 更多 >