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

标签 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未使用,因为在 fourthList 中的先前值和 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]]

这将排除使用 19在 secondList[1] 因为 047中减去后已经被删除

最佳答案

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]]

关于python - 从带有条件参数的列表列表中减去列表列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158351/

相关文章:

javascript - 检测表单是否已更改,脚本不起作用

javascript - 空 jQuery 字符串不为空

python - 在 python 中使用 BernoulliNB(朴素贝叶斯分类器)scikit-learn 的简单示例 - 无法解释分类

python字符串连接混淆

python - [django]当debug = false时,MEDIA_URL返回找不到

bash - 如何迭代 Bash 中变量定义的一系列数字?

vue.js - Vue.js 中以 </div> 结尾的条件标记

python - 在同一个conda环境中安装Python3.9和PyPy3.7

django - 如何检查 Django 模板中的最后一个循环迭代?

java - 对于循环执行,增加困惑