+ 2
Hello everyone, here is my question: if i want to count how many numbers are, before and after a single item in a list
E.g items = [1, 4, 5, 7, 3, 6, 9, 0, 10] So here, i want to count numbers before 3 in the items and after 3. How can I do it in python? Pls help me out.
13 Answers
+ 11
Mustapha Khalid Yakubu
Here is another option using the same concept as Daniel C
https://code.sololearn.com/cj31l8jx1g0F/?ref=app
+ 9
To do this, you should find the index of the desired number (for example, 3). Then, break the array into two subarrays around that index and get the length of both of them. This is best done by indexing using the : operator, as seen in my code below.
https://code.sololearn.com/cCbt5XBhn4q0/?ref=app
+ 6
here is a version that uses python *more_itertools* module, that has some great iteration tools. in this case i used *split_at()*
from more_itertools import split_at
items = [1, 4, 5, 7, 3, 6, 9, 0, 10]
inp = int(input())
print([len(i) for i in list(split_at(items, lambda n: n == inp))])
result: [4, 4]
the interesting thing is: if the input list contains more then 1 of the separator, it also works great:
items = [1, 4, 5, 7, 3, 6, 9, 3, 0, 10] # 3 occurs 2 times in the list
result: [4, 2, 2]
+ 6
Expanding on Lothar's solution, and making more general purpose:
https://code.sololearn.com/cOH3HAQmaqfG/?ref=app
+ 5
lst=[1, 4, 5, 7, 3, 6, 9, 0, 10]
strlst= str(lst).replace(", 3,","],[")
eval(f"print([len(i) for i in [{strlst}]])")
+ 3
Chidiebere Ogbuagu
The basics are easy to learn. About a month at most.
But learning is an ongoing process.
Coding languages are continually being updated, features added and deprecated.
So one tries to keep up to date, and try to learn and sometimes to unlearn things.
+ 2
Simple and clear.
Check This:
https://code.sololearn.com/ckqO3ufy64s5/?ref=app
+ 1
Thanks Rik Wittkopp, that's what I needed
+ 1
Chidiebere Ogbuagu I have learned 3 programming languages(bash, python, JavaScript) within 20 months. My goal is not to be a developer but to be able to write, and understand codes/scripts in different programming languages.
There is no actual length of learning, it depends on hours you dedicate to learn and practice.
+ 1
👍🏼👍🏼
0
How long did all of u learn to code
0
Use the index function of Python