data = {'time': 1603324800, 'url_shares': 50, 'social_score': 165122, 'volume': 98072509, 'market_cap': 75556475}, {'time': 1603411200, 'url_shares': 24, 'social_score': 49081, 'volume': 100253684, 'market_cap': 77036901}, {'time': 1603497600, 'url_shares': 11, 'social_score': 0, 'volume': 72689111, 'market_cap': 75257217}, {'time': 1603584000, 'url_shares': 6, 'social_score': 76225, 'volume': 71654076, 'market_cap': 71411043}, {'time': 1603670400, 'url_shares': 2, 'social_score': null, 'volume': 101958997, 'market_cap': 69759354},
我想將social_score除以其以前的social_score,如果為null/int,則應回傳null,如果為int/null,則應回傳int。但我不知道該怎么做。
uj5u.com熱心網友回復:
目前尚不完全清楚您的問題中的“以前”是什么意思,所以如果我弄錯了,請隨意交換這個答案中的角色i。i 1
null = ('__null__',)
data = {'time': 1603324800, 'url_shares': 50, 'social_score': 165122, 'volume': 98072509, 'market_cap': 75556475}, {'time': 1603411200, 'url_shares': 24, 'social_score': 49081, 'volume': 100253684, 'market_cap': 77036901}, {'time': 1603497600, 'url_shares': 11, 'social_score': 0, 'volume': 72689111, 'market_cap': 75257217}, {'time': 1603584000, 'url_shares': 6, 'social_score': 76225, 'volume': 71654076, 'market_cap': 71411043}, {'time': 1603670400, 'url_shares': 2, 'social_score': null, 'volume': 101958997, 'market_cap': 69759354},
results = []
for i in range(len(data)-1):
if data[i 1]['social_score'] not in (null, 0):
results.append(data[i]['social_score'] / data[i 1]['social_score'])
else:
results.append(data[i]['social_score'])
print(results)
# [3.364275381512194, 49081, 0.0, 76225]
或者,如果您不喜歡到處都有[ ]索引,請使用pairwise:
from itertools import pairwise
from operator import itemgetter
results = [
(x / y if y not in (null, 0) else x)
for x, y in pairwise(map(itemgetter('social_score'), data))
]
print(results)
# [3.364275381512194, 49081, 0.0, 76225]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/483273.html
上一篇:如何反轉連續的百分比計算?
下一篇:相對于中心縮放多邊形
