【问题标题】:Python append a string with if/else?Python 用 if/else 附加一个字符串?
【发布时间】:2019-07-10 17:43:55
【问题描述】:

我想根据if-else结果创建结果字符串列表,但目前运行循环时只能看到一个1值字符串。

例子:

for ips in npat:
    ipnet = ips.strip()
    print ("Processing ..... ", ipnet)
    fgen = "grep " +ipnet+ " /mnt/hgfs/IRR/fgen.txt"
    f2pat = re.findall(ipnet,fgen)
    print ("\nCommand: ",fgen)
    os.system(fgen)
    print ("\n NEW NPATH: ",f2pat)

    flist = []
    if ipnet in f2pat:
        flist.append("Grep Found")
        print ("Result ", flist)
    else:
        flist.append("Grep NotFound")
        print ("Result: ",flist)

flist -> ['Grep Found']...列表中只有 1 个值,尽管应该有多个值。我可以知道你的想法吗?

谢谢。

【问题讨论】:

  • 您是否尝试过将flist = [] 移动到您的for ips in npat 循环之外/上方?

标签: python python-3.x python-2.7 loops append


【解决方案1】:

似乎flist = [] 在循环中被重新初始化。将该变量单独移动到您的for loop 上方。因此代码变为:

flist = []
for ips in npat:
    ipnet = ips.strip()
    print ("Processing ..... ", ipnet)
    fgen = "grep " +ipnet+ " /mnt/hgfs/IRR/fgen.txt"
    f2pat = re.findall(ipnet,fgen)
    print ("\nCommand: ",fgen)
    os.system(fgen)
    print ("\n NEW NPATH: ",f2pat)


    if ipnet in f2pat:
        flist.append("Grep Found")
        print ("Result ", flist)
    else:
        flist.append("Grep NotFound")
        print ("Result: ",flist)

感谢 jedwards comment

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 2014-05-20
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    相关资源
    最近更新 更多