简体   繁体   中英

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

Why is list.index(x) not finding a match when I slice the index after position 0?

This statement correctly sets closed_order = 0.

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

But the statement below cannot find the value. I would expect it to return 4.

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

The if statement also correctly finds the match.

The entire code is shown below.

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

I am new to Python and appreciate the help. Thank you. Best regards, Sanjay

[2:] means "give me elements from 2 onward". [0] means "give me the first element". So trades[2:][0] means "give me the first element of the elements from 2 onward" -- which is the same as just trades[2] . That does not contain your strategy .

Likewise, in your first example, trades[:][0] is the same as trades[0] . This just happens to work for your example because trades[0] does contain your targeted strategy.

It's not clear what you think trades[2:][0] does, but maybe you're thinking that that the [0] means "give me the first element of each of the sub-lists". But that's not what it means. If you want that you'd have to use a list comprehension:

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

However, this will not give you 4, but 2, because by slicing trades you have changed where your new list starts. The element that used to be at position 4 is now at position 2, because you sliced 2 elements off at the beginning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM