![](/img/trans.png)
[英]making a list from values returned by a function inside a for-loop in python
[英]Calculate the total value of all values returned from a for-loop
我有一個 for 循環,它正在遍歷 IPS 列表,連接到設備,查找特定值,計算該值出現的次數,然后打印找到的次數。
我通過使用len()
function 來實現這一點。
見下面的代碼:
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)
以上代碼將以 output 為例:
1, 1, 1
2, 2, 2
我想要做的是最后,將所有這些值加在一起並打印總數,所以上面實際上會打印為:(對於每個值 1+2 = 3)
3, 3, 3
我嘗試使用sum()
,並將我的 print 語句放在for
循環之外,但這不起作用。
你可以通過使用內置的sum()
function 和itertools.zip_longest()
來相當容易地做到這一點。
當然,我無法在您的問題中運行代碼,但這里有一些示例代碼可以讓您了解如何做類似的事情:
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:
1 2 3
2 3 4
3 4 5
totals: [6, 9, 12]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.