[英]How to get for loop to move onto the next inner list?
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.
我的代码输出 2,因为它只通过第一个内部列表。
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 return语句在第一个for 内,因此在第一行之后它将返回并退出函数
also, list has a built-in function count , that can be used to make the code a little simples and faster:此外, list 有一个内置函数count ,可用于使代码更简单和更快:
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找到的第一个函数:600
time: 0.0003502368927001953时间:0.0003502368927001953
second function found: 600找到的第二个函数:600
time: 0.000194549560546875时间:0.000194549560546875
Correct the return
indent更正
return
缩进
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它打印 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.