3 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
我對(duì)這個(gè)問題的看法:
from collections import Counter
testlist = ['red','red','blue','red','red','black','yellow','black','yellow','blue']
def changes(data):
last = data[0]
for i in data:
if last != i:
yield i
last = i
c = Counter(changes(testlist))
c['key'] = 40006
print(dict(c))
輸出:
{'yellow': 2, 'red': 1, 'key': 40006, 'blue': 2, 'black': 2}

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個(gè)贊
我的zip習(xí)慣是成對(duì)瀏覽列表,非常簡(jiǎn)潔。與其他Counter工具一樣,它使用,我同意這是完成這項(xiàng)工作的正確工具。
from collections import Counter
testlist = ['red','red','blue','red','red','black','yellow','black','yellow','blue']
def count_changes(data):
c = Counter()
c['key'] = 40006
for item1, item2 in zip(data, data[1:]):
if item1 != item2:
c[item2] += 1
return c
print(count_changes(testlist))
輸出:
Counter({'key': 40006, 'blue': 2, 'black': 2, 'yellow': 2, 'red': 1})
尚不清楚如果"key"出現(xiàn)在測(cè)試列表中,正確的行為應(yīng)該是什么,但是修改此代碼以解決該問題很簡(jiǎn)單。

TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
首先,由于您的目標(biāo)是構(gòu)建一個(gè)dict,所以只需動(dòng)態(tài)構(gòu)建該dict,而不是構(gòu)建一堆單獨(dú)的變量,然后將它們放在dict的末尾即可。
您也可以使用Counter而不是Plain dict,因此您不必?fù)?dān)心檢查顏色是否已經(jīng)存在。
當(dāng)我們使用它時(shí),不需要調(diào)用str已經(jīng)是字符串的東西,并且到處都有很多不必要的parens。
所以:
from collections import Counter
dictfordf = Counter()
dictfordf['key'] = 40006
for i in range(len(testlist)-1):
if testlist[i] == testlist[i+1]:
print("No Change")
else:
print("Change to: " + testlist[i+1])
dictfordf[testlist[i+1]] += 1
這是一個(gè)有點(diǎn)哈克來存儲(chǔ)一個(gè)值'key',真正是不是算的,所以你可能要考慮使用defaultdict,或setdefault在普通字典,來代替。但我認(rèn)為這并不算太糟。
當(dāng)然,如果'key'可能是中的元素之一,則將testlist增加密鑰。不過,如果這是可能的,目前還不清楚是什么應(yīng)該在這種情況下發(fā)生的,所以目前還不清楚你要如何解決它。
同時(shí),您可以通過遍歷相鄰對(duì)來簡(jiǎn)化事情。請(qǐng)參閱文檔中的pairwise食譜itertools。但是,當(dāng)然這會(huì)在pairwise代碼中添加的定義(或者您可以從第三方庫(如more-itertools或toolz)導(dǎo)入它的定義。
所以:
from collections import Counter
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
dictfordf = Counter()
dictfordf['key'] = 40006
for prev, current in pairwise(testlist):
if prev == current:
print("No Change")
else:
print("Change to: " + current)
dictfordf[current] += 1
您可以使用groupby或的unique_justseen配方進(jìn)一步抽象事物itertools。我認(rèn)為這會(huì)掩蓋而不是澄清您print的輸出結(jié)果,但是,假設(shè)您了解pairwise版本,則值得閱讀它們的兩個(gè)部分,并至少在練習(xí)中嘗試編寫這兩種選擇。
添加回答
舉報(bào)