I'm trying to count the number of zeros within a nested list. My code outputs 2 because it only goes through the first inner list.
This is what I have currently:
def e(xlst):
cnt = 0
for numbers in xlst:
for numbers2 in numbers:
if numbers2 == 0:
cnt += 1
return cnt
xlst = [[1,0,0],[1,1,1],[1,1,0]]
e(xlst)
您放错了return
,它应该与外部循环匹配
The return statement is inside the first for , so after the first row it will return and exit the function
also, list has a built-in function count , that can be used to make the code a little simples and faster:
from time import time
def e(xlst):
cnt = 0
for numbers in xlst:
for numbers2 in numbers:
if numbers2 == 0:
cnt += 1
return cnt
def with_count(xlst):
cnt = 0
for numbers in xlst:
cnt += numbers.count(0)
return cnt
# Creates a 2D list with 300 rows of [1,0,0]
xlst = [[1,0,0]]*300
t0=time()
print(f'\nfirst function found: {e(xlst)}')
print(f'time: {time() - t0}\n')
t0=time()
print(f'second function found: {with_count(xlst)}')
print(f'time: {time() - t0}\n')
first function found: 600
time: 0.0003502368927001953
second function found: 600
time: 0.000194549560546875
Correct the return
indent
Code should be like this
def e(xlst):
cnt = 0
for numbers in xlst:
for numbers2 in numbers:
if numbers2 == 0:
cnt += 1
return cnt
xlst = [[1,0,0],[1,1,1],[1,1,0]]
print(e(xlst))
It prints 3
Using global variables is bad practice, but I am too tired to figure out how to do it without, without using two functions
def e(xlst):
cnt = 0
if (type(xlst) == list):
for x in xlst:
e(x)
elif (xlst == 0):
cnt +=1
Here we use recursion, calling the function on each nested list. This works for infinitely nested lists.
You could do it as a one liner.
from itertools import chain
def e(xlst):
return len([i for i in chain.from_iterable(xlst) if i == 0])
xlst = [[1,0,0],[1,1,1],[1,1,0]]
print(e(xlst))
or without the temporary list.
def e(xlst):
return sum(1 for i in chain.from_iterable(xlst) if i == 0)
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.