Ask Your Question
1

strange result when finding the index of a boolean list

asked 2022-03-02 16:13:06 +0200

Cyrille gravatar image

updated 2022-03-02 16:59:26 +0200

John Palmieri suggest to use v.startswith('$a_') in answer to my former question How to construct a condition on the family name of a variable without notice to its index.

Here is a little program

RR=['$x_{0}$',
 '$x_{1}$',
 '$x_{2}$',
 '$a_{3}$',
 '$\\varepsilon_{4}$',
 '$a_{5}$',
 '$\\varepsilon_{6}$']
OB=[v.startswith('$a_') for v in RR]
SS=[OB.index(v) for v in OB if v==True]
SS

which give the answer [3,3] when in my eyes the answer should be [3,5]. I know this is the standard process to gives the first occurence of the string. But why there is not a defined function which gives all the indexes ?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-03-02 17:08:36 +0200

As you note, that's how indexworks: it returns the index of the first element that matches. There are ways of finding all occurrences of an element in a list: see for example https://stackoverflow.com/questions/6.... That leads to

[i for i, v in enumerate(OB) if v==True]

or slightly more briefly

[i for i, v in enumerate(OB) if v]

or skipping OB

[i for i, v in enumerate(RR) if v.startswith('$a_')]

(enumerate is documented here.)

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2022-03-02 16:13:06 +0200

Seen: 34 times

Last updated: Mar 02