Python 从一个列表中删除另一个列表中的元素,但不完全删除该值
我有一个项目,其中我必须根据参数listA的长度划分2个列表,数字必须按升序排列,其余元素进入列表BPython 从一个列表中删除另一个列表中的元素,但不完全删除该值,python,list,partitioning,Python,List,Partitioning,我有一个项目,其中我必须根据参数listA的长度划分2个列表,数字必须按升序排列,其余元素进入列表B def partitionLists(listA, listB, largerFirst=False): if largerFirst == False: sortedA = [] listCombination = listA + listB listCombination.sort() for i in range(len(listA)): i
def partitionLists(listA, listB, largerFirst=False):
if largerFirst == False:
sortedA = []
listCombination = listA + listB
listCombination.sort()
for i in range(len(listA)):
if listCombination[i] <= listCombination[i + 1]:
sortedA.append(listCombination[i])
def分区列表(listA、listB、largerFirst=False):
如果largerFirst==False:
sortedA=[]
listCombination=listA+listB
listCombination.sort()
对于范围内的i(len(listA)):
如果listCombination[i]您可以使用第一个列表上的迭代器来执行此操作,该迭代器将告诉您要跳过第二个列表中的哪些元素(假设两个列表都已排序): 输出:
a = [1, 1, 3, 3, 4, 4, 5, 5]
b = [1, 1, 3, 3, 4, 4, 5, 5, 5, 6, 7, 7, 34, 45, 56, 65, 432, 543, 723]
c = removeList(a,b)
print(c)
# [5, 6, 7, 7, 34, 45, 56, 65, 432, 543, 723]
[编辑]如果列表A中可能存在列表B中不存在的数字,则需要调整方法以跳过这些值:
def removeList(listA,listB):
iterA = iter(listA)
valueA = next(iterA,None)
result = []
for valueB in listB:
while valueA is not None and valueA < valueB:
valueA = next(iterA,None) # skip values in listA that are not in listB
if valueB == valueA:
valueA = next(iterA,None)
else:
result.append(valueB)
return result
a = [1, 1, 3, 3, 4, 4, 4, 5, 5, 8]
b = [1, 1, 3, 3, 4, 4, 5, 5, 5, 6, 7, 7, 34, 45, 56, 65, 432, 543, 723]
c = removeList(a,b)
print(c)
# [5, 6, 7, 7, 34, 45, 56, 65, 432, 543, 723]
def removeList(列表A、列表B):
iterA=国际热核实验堆(listA)
valueA=下一个(iterA,无)
结果=[]
对于列表B中的值B:
当valueA不是None且valueA小写形式。是的,ty工作得很好,以前从未使用过迭代器,它肯定会研究这一点,谢谢你是的,那也行我想我太有远见了,对较小的列表进行排序,检查它们的索引是否相等,如果相等就删除它们
def removeList(listA,listB):
iterA = iter(listA)
valueA = next(iterA,None)
result = []
for valueB in listB:
while valueA is not None and valueA < valueB:
valueA = next(iterA,None) # skip values in listA that are not in listB
if valueB == valueA:
valueA = next(iterA,None)
else:
result.append(valueB)
return result
a = [1, 1, 3, 3, 4, 4, 4, 5, 5, 8]
b = [1, 1, 3, 3, 4, 4, 5, 5, 5, 6, 7, 7, 34, 45, 56, 65, 432, 543, 723]
c = removeList(a,b)
print(c)
# [5, 6, 7, 7, 34, 45, 56, 65, 432, 543, 723]