如何在Python中以数学方式减去两个列表中的项目并仅输出满足条件的项目? [英] How to mathematically subtract items in two lists in Python and only output those items which meet a condition?
问题描述
我有两个列表已经从低到高排序:
I have two lists that are already sorted from low to high:
A=['40','60','80']
B=['10','42','100']
我想用B中的每个项目减去A中的每个项目.然后,如果这些值之间的差满足一个条件,特别是如果小于5,则从输出应为以下内容的每个列表中删除这两个项目:
I want to subtract each item in A by every item in B. Then, if the difference between these values meets a condition, specifically, if less than 5, then delete both items from each list where the output should be:
A=['60','80']
B=['10','100']
**有时列表的长度不相等,有时每个列表中只有1个项目
**Sometimes lists are unequal in length, and sometimes there are only 1 item in each list
我找到了许多方法来减去列表中的项目,但是我不知道如何检索和删除指定列表中的特定项目,或者它们仅从相反列表中的每个对应项目中减去一项.
I have found many ways to subtract items in lists, but I do not know how to retrieve and delete the specific items in the specified lists, or they only subtract one item from each corresponding item in the opposite list
使用lambda:
如果list(imap(lambda m,n:m-n< 5,A,B))==真:
if list(imap(lambda m, n: m-n < 5, A, B)) == True:
使用imap,sub
Using imap,sub
list(imap(sub, A, B)):
使用Numpy
M = np.array([A])
N = np.array([B])
c = abs(M-N)
非常感谢.
推荐答案
不使用numpy:
A = ["40", "60", "80"]
B = ["10", "42", "100"]
newA = filter(lambda a: all([abs(int(a) - int(b)) >= 5 for b in B]), A)
newB = filter(lambda b: all([abs(int(a) - int(b)) >= 5 for a in A]), B)
print newA
print newB
这篇关于如何在Python中以数学方式减去两个列表中的项目并仅输出满足条件的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!