比率列表:构建值列表除以字典列表中的先前值

List of ratios: build list of value divided by previous value in list of dict

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 它应该 return 为空,如果 int/null 它应该return 整数。但我不知道该怎么做。

您的问题中“上一个”的含义并不完全清楚,所以如果我弄错了,请随意交换此答案中 ii+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]