Python用if / else附加一个字符串?

问题描述 投票:1回答:1

我想基于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)

qazxsw poi ...尽管应该有多个值,但列表中只有1个值。我可以知道你的想法吗?

谢谢。

python python-3.x python-2.7 loops append
1个回答
4
投票

似乎flist -> ['Grep Found']在循环中被重新定位。将该变量单独移动到flist = []上方。因此代码变成:

for loop

积分jedwards 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)

© www.soinside.com 2019 - 2024. All rights reserved.