我有兩個由一系列正數或負陣列成的串列,兩個串列的長度可能不相等,如下所示:
lst1 = [2, 3, 3, 5, 6, 6, 6, 8, 10]
lst2 = [-1, -2, -2, -3, -6, -10, -11]
我想要得到的結果是:
lst_ofs = [-1, -2, 3, 5, 6, 6, 8, -11]
兩個串列中絕對值相等的正負數被數量抵消,有沒有簡單的方法可以做到這一點?
uj5u.com熱心網友回復:
該解決方案將每個數字的正面和負面實體的數量計算到最大值。根據需要在每次迭代中擴展輸出串列。
lst1 = [2, 3, 3, 5, 6, 6, 6, 8, 10]
lst2 = [-1, -2, -2, -3, -6, -10, -11]
lst_ofs = []
for i in range(max(max(lst1), -min(lst2)) 1):
n = lst1.count(i) - lst2.count(-i)
if abs(n) > 0:
lst_ofs.extend([int(i * n / abs(n))] * abs(n))
print(lst_ofs)
輸出:
[-1, -2, 3, 5, 6, 6, 8, -11]
uj5u.com熱心網友回復:
result = lst1 lst2
# keep checking for pairs until none are left
while True:
for v in result:
if -v in result:
# if v and -v are in the list, remove them both
# and restart the for loop
result.remove(v)
result.remove(-v)
break
else:
# if the for loop made it all the way to the end,
# break the outer loop
break
這不是最有效的解決方案,因為for每次洗掉兩個值時回圈都會重新開始。但它應該作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/466045.html
上一篇:迭代拆分串列元素
下一篇:按多個分隔的數字對字串進行排序
