有一個串列,如:
>>> l = [0, 1, 1, 1, 0, 2, 2, 2, 0]
我如何實作一個計算重復數字總和的代理,并且索引操作的行為如下:
>>> proxy = Proxy(l)
>>> proxy[0]
0
>>> proxy[1]
3
>>> proxy[2]
0
>>> proxy[3]
6
>>> proxy[4]
0
底層串列必須是不變的。代理將是一個接收串列并實作getitem 的類,例如:
class Proxy:
def __init__(self, l):
self.l = l
def __getitem__(self, index):
pass
我需要在getitem方法中進行某種“即時”計算。我需要保持串列絕對不變,以便利用一些框架。
uj5u.com熱心網友回復:
您可以使用itertools.groupby和sum:
from itertools import groupby
proxy = lambda lst: [sum(g) for _, g in groupby(lst)]
p = proxy([0, 1, 1, 1, 0, 2, 2, 2, 0])
p
# [0, 3, 0, 6, 0]
或者作為一個類:
class Proxy:
def __init__(self, l):
self.l = l
self._data = [sum(g) for _, g in groupby(iterable)]
def __getitem__(self, index):
return self._data[index]
一些檔案:
itertools.groupbysum
uj5u.com熱心網友回復:
我不太明白你的問題。但是我已經實作了一個簡單的函式來按照你的意愿去做。(或者至少我認為你想要的)
def Proxy(lst):
result = [0]
last_value = lst[0]
for item in lst:
if item == last_value:
result[len(result)-1] = item
else:
result.append(item)
last_value = item
return result
uj5u.com熱心網友回復:
我會簡單地迭代串列,保留之前的值進行比較。就像是:
from typing import List
def proxy(lst: List[int]):
res = {}
prev = None # Initial value, would be different from first item
index = -1 # Initial value, would be incremented on first item
for num in lst:
if num == prev:
res[index] = num
else:
index = 1
res[index] = num
prev = num
return res
uj5u.com熱心網友回復:
from collections import Counter
class View:
def __init__(self, l):
self.l = Counter(l)
def __getitem__(self, index):
return self.l.get(index, 0) * index
proxy = View([0, 1, 1, 1, 0, 2, 2, 2, 0])
print(proxy[2]) #6
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/347431.html
上一篇:重塑串列/陣列
