【问题标题】:How to append an output that is looping rather than making each loop its own line如何附加循环的输出而不是使每个循环成为自己的行
【发布时间】:2020-05-30 07:34:42
【问题描述】:

我阅读了一些类似的问题,但对我的情况没有任何帮助。我有一个循环遍历 csv 文件并提取 IP。然后,我想将这些 IP 串起来,正如您在下面的代码中所见的“添加 =”。如何让字符串 IP 在每次添加时都追加,而不是每次都换行?

代码尝试:

for i in x['Agent IP']:
    data = (i) 
    adding = {'field': 'ip-address', 'operator': 'is', 'value': str(data)}
    print(adding)

收到的输出:

{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.1'}
{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.2'}
{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.3'}
{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.4'}

我希望输出在它们之间附加一个共同点,如下所示:

{'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.1'}, {'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.2'}, {'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.3'}, {'field': 'ip-address', 'operator': 'is', 'value': '192.168.0.4'}

【问题讨论】:

  • 你用append标记了你的问题;你为什么不尝试使用它?

标签: python loops append


【解决方案1】:

我认为您正在寻找一个列表:

res = []

for i in x['Agent IP']:
    data = (i) 
    adding = {'field': 'ip-address', 'operator': 'is', 'value': str(data)}
    res.append(adding)

print(res)

【讨论】:

    【解决方案2】:

    您可以创建一个列表并附加它,而不是将其打印出来,这样您就可以在代码的开头调用information = list(),在您的打印函数所在的位置您可以调用information.append(adding),在文件的末尾您可以调用可以拨打print(information)

    【讨论】:

      猜你喜欢
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 2013-04-25
      • 2020-08-22
      • 2012-01-27
      • 1970-01-01
      • 2016-02-11
      相关资源
      最近更新 更多