从带有条件参数的列表列表中减去列表列表

时间:2015-05-11 01:10:09

标签: python for-loop conditional-statements nested-lists subtraction

我有一个棘手的问题,我很难缠头。

我有两个列表列表:

firstList = [[0, 9], [0, 4], [0]]
secondList = [[18], [19, 7], [20]]

我想从firstList中的值按升序减去secondList中的值,但如果firstList中的值为,则已经被“使用”了。例如:

thirdList = [0,4]
fourthList = [19,7]
emptyList = []

emptyList.append(fourthList-thirdList]
print(emptyList)
>>>[7,3]

在这种情况下,未使用19,因为第四个列表中的上一个值与19

之间的thirdList中没有值

我正在考虑这样的事情(尽管它很快会分解成伪代码)

firstList = [[0, 9], [0, 4], [0]]
secondList = [[18], [19, 7], [20]]
emptyList = [ [] for y in range(3) ]

for x in range(3) :
    #for smallest value in secondList[x], subtract all smaller values in firstList and then delete them, append values to emptyList[x]
    #for next smallest value in secondList[x], subtract all smaller values in firstList and then delete them, append values to emptyList[x]
    #repeat until firstList is empty, then exit loop

print(emptyList)
>>>[[9, 18], [3, 7], [20]]

这将排除在secondList [1]中使用19,因为从0

中扣除后47已被删除

1 个答案:

答案 0 :(得分:1)

firstList = [[0, 9], [0, 4], [0]]
secondList = [[18], [19, 7], [20]]
all_results = []

for x in range(0, len(firstList)):  
    values_of_first = firstList[x]
    values_of_second = secondList[x]
    values_of_first.sort()
    values_of_second.sort()  
    tmp_results = []

    for subtractor in values_of_second:    
        used_values = []
        for subtracted in values_of_first:
            if subtracted >= subtractor:
                break
            else:
                used_values.append(subtracted)
                tmp_results.append(subtractor - subtracted)

        for used_value in used_values:
            values_of_first.remove(used_value)

    tmp_results.sort()
    all_results.append(tmp_results)

它产生all_results == [[9, 18], [3, 7], [20]]