I want to count the number of non-None elements appearing while resetting every time None appears in Python.

Asked 1 years ago, Updated 1 years ago, 201 views

I'm a beginner. I'd like to know how many times in a row the 0.1.2.3rd in each of the two-dimensional lists in Python until None appears, and how to program the reset when None appears.

Input:

listA=[0,-1,1,0],
         [1, 0, -1, 1],
         [0, 1, None, 1],
         [-1, None, 0, 1]

Output:

 [4,0,1,4]

In this way, the number 0 in the list continued four times in a row, so I would like to print 4 times in a row, 4 times in a row, 0 times in a reset, and 4 times in a row without a single.Thank you for your cooperation.

python

2022-11-06 08:18

3 Answers

>>[i[::-1].index(None) if None in self(i) for i in zip(*listA)]
[4, 0, 1, 4]


2022-11-06 22:59

  • Count from top to bottom
  • Reset the count to 0 each time
  • None appears

If you think about it the other way around,

  • Counting from the tail to the top
  • Stop counting when
  • 0 appears

is the case.The latter should be as efficient as the algorithm can omit the subsequent count when 0.If you write this, for example, it will look like this:

listA=[0,-1,1,0],
         [1, 0, -1, 1],
         [0, 1, None, 1],
         [-1, None, 0, 1]

width=len(listA[0])
height=len(listA)

result=[0]*width

# Count up from 0 to (width-1)
for win range (width):
    # Countdown from (height-1) to 0
    for hin range (height-1, -1, -1):
        # Stop the current count when None appears.
        if listA[h][w] == None:
            break
        result[w]+=1

print(f"{result=}")


2022-11-07 04:02

I wrote down the numbers in a function, and I wrote down the parts that I looked up vertically (in a column).

listA=[0,-1,1,0],
         [ 1, 0, -1, 1],
         [0, 1, None, 1],
         [-1, None, 0, 1]

defcnt(lst):
    n = 0
    for vinst:
        n = 0 if v is None elsen + 1
    return n

result = [cnt([listA[i][j]] for i in range (len(listA))])
          for jin range (len(listA[0]))]

print(result)
 [4,0,1,4]


2022-11-07 04:15

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.