为什么list.index(x)在位置0之后切成索引时找不到匹配?
此语句正确设置了loss_order = 0。
closed_order = trades[:][0].index(strategy)
但是下面的说明找不到该值。我希望它返回4.
closed_order = trades[2:][0].index(strategy)
if语句也正确找到了匹配。
整个代码如下所示。
from decimal import Decimal, getcontext
getcontext().prec = 2
trades = [['shp_str_sl_17_(Clsd Prft)', '12/18/11', Decimal('4.66')],
['shp_str_sl_17_(Re)', '12/18/11', Decimal('4.61')],
['shp_str_sl_17_(Re)', '1/22/12', Decimal('5.62')],
['shp_str_sl_17_(OBV X^)', '1/29/12', Decimal('6.63')],
['shp_str_sl_17_(Clsd Prft)', '3/11/12', Decimal('6.84')],
['shp_str_sl_17_(UDR 0^)', '7/29/12', Decimal('5.03')],
['shp_str_sl_17_(Clsd Prft)', '10/28/12', Decimal('5.60')]]
strategy = 'shp_str_sl_17_(Clsd Prft)'
if trades[4][0] == strategy:
print "match found"
closed_order = trades[2:][0].index(strategy)
print "closed_order=",closed_order
我是Python的新手,并感谢您的帮助。谢谢。此致,Sanjay
[2:]
的意思是"给我2开始的元素"。[0]
的意思是"给我第一个元素"。因此,trades[2:][0]
的意思是"给我2个元素的第一个元素",这与trades[2]
相同。那不包含您的strategy
。
同样,在您的第一个示例中,trades[:][0]
与trades[0]
相同。这恰好适合您的示例,因为trades[0]
确实包含了您的目标策略。
尚不清楚您认为trades[2:][0]
的作用,但是也许您认为[0]
的意思是"给我每个子名单的第一个元素"。但这不是什么意思。如果您愿意,必须使用列表理解:
[sub_list[0] for sub_list in trades[2:]].index(strategy)
但是,这不会给您4,而是2,因为通过切片trades
,您已更改了新列表开始的位置。过去位于位置4的元素现在位于位置2,因为您在开始时切了2个元素。