元组比较

2024-10-03 15:26:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典是这样定义的:

d = {"date": tuple(date),"open":tuple(open),"close":tuple(close),"min":tuple(min),"max":tuple(max),"MA":tuple(ma)}

这些元组中的每一个都包含一个值列表(每个元组的值数目相同),如果“close”优于“MA”,我如何遍历每个分键的值来进行比较?在


Tags: 列表closedate字典定义openminmax
2条回答

我错过了什么?d['close'] > d['MA']?在

编辑:Re,你的评论

[...] what I want to return is how many times one element of "close" is > to the matching element of MA . (same tuple index)

sum( pair[0] > pair[1] for pair in zip(d['close'], d['MA']) )

Python docs

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).

因此,正如@TokenMacGuy所说,您可以简单地使用d['close'] > d['MA']来比较各自的元组。在

相关问题 更多 >