[英]Deleting matching items from a list
我有一個值列表。 我想刪除相互抵消的值(+ 和 -)。 這些值在列表中是隨機的,所以我首先在 excel 中添加了一個包含絕對值的新列。 然后我對絕對值進行排序,因此需要取消的金額低於彼此。
我想創建一個 for 循環並將第一行與第二行相加,當總和為零時,刪除兩行並再次從頂部開始。 請參考示例圖片。 我已將應刪除的項目標記為黃色。 由於我只想刪除匹配項,操作后amount列的總和應該不會改變。
目前我有這樣的東西
for i in df["實體貨幣金額"]: if df["實體貨幣金額"][i] + df["實體貨幣金額"][i+1] == 0: df.drop(df [df["實體貨幣金額"][i]]) df.drop(df[df["實體貨幣金額"][i + 1]])
在對列表進行排序后嘗試這樣的操作(正如您已經說過的):
for i,elem in enumerate(yourList):
nextElem = yourList[i+1]
if (elem + nextElem < 0.00000001):
yourList.remove(elem)
yourList.remove(nextElem)
我會根據幾個構建塊來回答。 首先是創建兩個“可迭代”子列表。 一個用於正數,另一個用於負數。
然后我將使用next()
遍歷它們兩個,只要兩個列表之一有值,我就會適當地對當前值采取行動。
import random
full_data = [random.randint(0, 10) for _ in range(20)] + [-random.randint(0, 10) for _ in range(20)]
zeros = [i for i in full_data if i == 0]
positives = iter(sorted([i for i in full_data if i > 0]))
negatives = iter(sorted([i for i in full_data if i < 0], reverse=True))
## ------------------------------
## prime the list with zero or 1 0s where an odd number of 0s
## results in [0] as the evens cancel each other out.
## ------------------------------
result = [0] * (len(zeros) % 2)
## ------------------------------
pos = next(positives, None)
neg = next(negatives, None)
while pos is not None or neg is not None:
if pos is None:
# we ran out of positive numbers so add any remaining negatives
result.extend([neg] + list(negatives))
break
if neg is None:
# we ran out of negative numbers so add any remaining positives
result.extend([pos] + list(positives))
break
if pos == -neg:
# these results cancel each other
pos = next(positives, None)
neg = next(negatives, None)
elif pos > -neg:
# this positive is "larger" then this negative so add the negative
result.append(neg)
neg = next(negatives, None)
else:
# this positive is "smaller" than this negative so add the positive
result.append(pos)
pos = next(positives, None)
print(f"The original list has {len(full_data)} items and sums to: {sum(full_data)}")
print(f"The filtered list has {len(result)} items and sums to: {sum(result)}")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.