python - 尝试使用 2 列

标签 python if-statement

基本上,这段代码的目标是报告一组设备上的哪些端口正在被使用。

代码如下:

`$` file_name = input('Enter File Name: ') + str('.csv')
total_ports = 500

my_reader = csv.reader(open(file_name))
ctr = 0
for total_reserved in my_reader:
    if total_reserved[2] == 'Reserved':
        ctr += 1
print(ctr, 'out of ', total_ports, 'PLS ports are reserved')

my_reader = csv.reader(open(file_name))
ctr_pls0 = 0
for pls0 in my_reader:
    if pls0[0] == 'L1 switches/L1 Switch 10G PLS0.BLLAB/Blade01' and total_reserved[2]  == 'Reserved':
      ctr_pls0 += 1

print(ctr_pls0, 'of these', ctr, 'are pls0 ports') `$`

这给了我以下输出...

Enter File Name: 31.05.2018
175 out of  500 PLS ports are reserved
0 of these 175 are pls0 ports

Process finished with exit code 0

0 of these 175 are pls0 ports这就是问题所在,这一行应该为我提供名为 'L1 switches/L1 Switch 10G PLS.BLLAB/Blade01' 的端口数量。 AND 显示为 'Reserved' 根据 .csv 文件。

你知道这可能是什么吗?

谢谢!

最佳答案

在第二个循环中,您应该使用 pls0[2],而不是 total_reserved[2]total_reserved 包含第一个循环中文件的最后一行。

但是根本没有必要进行两个循环,只需在第一个循环中增加两个变量即可。

with csv.reader(open(file_name)) as my_reader:
    ctr = 0
    ctr_pls0 = 0
    for total_reserved in my_reader:
        if total_reserved[2] == 'Reserved':
            ctr += 1
            if total_reserved[0] == 'L1 switches/L1 Switch 10G PLS0.BLLAB/Blade01'
                ctr_pls0 += 1
print(ctr, 'out of ', total_ports, 'PLS ports are reserved')
print(ctr_pls0, 'of these', ctr, 'are pls0 ports') `$`

关于python - 尝试使用 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50628206/

相关文章:

c++ - If 语句没有正确读取 char 变量

python - 如何根据用户输入打印一个多面体的体积?

python - 导入 python 模块 - ImageChops

python - pyopengl 缓冲区从 numpy 数组动态读取

python - 这个网页登录Python脚本正确吗?

python - 如何在 Django 模板中使用 Humanize 显示 "x days ago"类型时间?

javascript - if 语句未在第三个按钮单击上注册

javascript - IF 语句并返回到函数的开头

powershell - PowerShell测试连接,如果使用get-service存在服务

python - 循环处理字符串