Python: List.Index(x), list 在位置 0 之后切片时找不到值

Python: List.Index(x), fails to find value when list is sliced after position 0

当我在位置 0 之后切片索引时,为什么 list.index(x) 找不到匹配项?

此语句正确设置 closed_order = 0。

closed_order = trades[:][0].index(strategy)

但是下面的语句找不到值。我希望它 return 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 的新手,感谢您的帮助。 谢谢你。 此致, 桑杰

[2:] 表示 "give me elements from 2 onward"。 [0] 表示 "give me the first element"。所以 trades[2:][0] 表示 "give me the first element of the elements from 2 onward" —— 与 trades[2] 相同。那不包含你的 strategy.

同样,在您的第一个示例中,trades[:][0]trades[0] 相同。这恰好适用于您的示例,因为 trades[0] 确实包含您的目标策略。

不清楚您认为 trades[2:][0] 的作用,但也许您认为 [0] 意味着 "give me the first element of each of the sub-lists"。但这不是它的意思。如果你想要,你必须使用列表理解:

[sub_list[0] for sub_list in trades[2:]].index(strategy)

但是,这不会给您 4,而是 2,因为通过切片 trades 您已经更改了新列表的开始位置。原来在位置4的元素现在在位置2,因为你在开头切掉了2个元素。