【问题标题】:How do I take manual inputs in python for a for loop?如何在 python 中为 for 循环手动输入?
【发布时间】:2019-06-28 15:30:01
【问题描述】:

我正在尝试手动输入并在 for 循环中使用这些输入在 CSV 文件中输出结果,但我无法让它工作。

我试图在 for 循环之外创建一个输入变量,该变量接受一个似乎没有传递到 for 循环中的 int 值。我还尝试手动输入内存量和操作系统名称。目标是吐出服务器名称。

CSV 文件:

Name,CPU,Memory,OS
server1,2,4gb,windows 7
server2,4,2gb,arch linux
server3,8,4gb,ubuntu linux
server4,4,2gb,windows server
server5,2,4gb,windows 7

Python 代码:

import csv


entercpu = int (input("Enter number of CPU: "))
#enteros = input("Enter the OS: ")
#entermemory = input("Enter the amount of memory: ")


with open('test.csv', 'rb') as csv_file:
    dict_reader = csv.DictReader(csv_file)

    for d in dict_reader:

        if d['NumCpu'] == 'entercpu' and d['Guest OS'] == 'windows 7' and d['MemoryGB'] == '8':
            print('Name: {Name}, CPU: {NumCpu}, Memory: {MemoryGB}, OS: {Guest OS}'.format(**d))

输出应该是: 名称: Name: Server 1, CPU: 4, Memory: 8, OS: windows 7
Name: Server 5, CPU: 4, Memory: 8, OS: windows 7

【问题讨论】:

  • 'entercpu' 只会产生字符串文字"entercpu"。你想要的可能是str(entercpu)(或者在脚本开头根本不将entercpu转换为int

标签: python csv parsing


【解决方案1】:

试试这个:

if d['NumCpu'] == str(entercpu) and d['Guest OS'] == 'windows 7' and d['MemoryGB'] == '8':
            print('Name: {Name}, CPU: {NumCpu}, Memory: {MemoryGB}, OS: {Guest OS}'.format(**d))

当你比较它们时,你需要确保你的类型是相同的。例如4 == "4" 返回Falsestr(4) == "4" 给出True

我认为当您键入 'entercpu' 时,这就是您的意思,但是当您尝试从一种或另一种类型进行转换时,您调用了构造函数(即str(4)int("4"))。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2014-06-02
    • 2015-08-26
    • 2019-01-18
    • 1970-01-01
    • 2020-12-17
    • 2021-05-08
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多