[英]Calculate the total value of all values returned from a for-loop
I have a for loop which is going through a list of IPS, connecting to a device, finding a specific value, calculating how many times this value is present, and then printing the number of times it is found.我有一个 for 循环,它正在遍历 IPS 列表,连接到设备,查找特定值,计算该值出现的次数,然后打印找到的次数。
I achieve this by using the len()
function.我通过使用
len()
function 来实现这一点。
See below code:见下面的代码:
for line in IPS:
try:
IPS = line.strip()
device = ConnectHandler(device_type=platform, ip=IPS, username=username,
password=password)
connectedregex = len(re.findall(r"connected", output))
notconnectregex = len(re.findall(r"notconnect", output))
errdisable = len(re.findall(r"errdisable", output))
print(connectedregex, notconnectregex, errdisable)
The above code will output as an example:以上代码将以 output 为例:
1, 1, 1
2, 2, 2
What I would like to do, is at the end, add all these values together and just print the total, so the above would actually print as: (for each value 1+2 = 3)我想要做的是最后,将所有这些值加在一起并打印总数,所以上面实际上会打印为:(对于每个值 1+2 = 3)
3, 3, 3
I have tried using sum()
, and taking my print statement outside the for
loop, however this does not work.我尝试使用
sum()
,并将我的 print 语句放在for
循环之外,但这不起作用。
You can do it fairly easily by using the built-in sum()
function in conjunction with itertools.zip_longest()
.你可以通过使用内置的
sum()
function 和itertools.zip_longest()
来相当容易地做到这一点。
I can't run the code in your question of course, but here's some sample code that should give you the idea of how to do something similar:当然,我无法在您的问题中运行代码,但这里有一些示例代码可以让您了解如何做类似的事情:
from itertools import zip_longest
IPS = [(1, 2, 3), (2, 3, 4), (3, 4, 5)]
totals = []
for line in IPS:
connected, notconnect, errdisable = line
print(connected, notconnect, errdisable)
totals = [sum(values) for values in
zip_longest(totals, (connected, notconnect, errdisable),
fillvalue=0)]
print()
print('totals:', totals)
Output: Output:
1 2 3
2 3 4
3 4 5
totals: [6, 9, 12]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.