Python 如何在配置文件中为单个键分配 2 个值,逗号分隔



我有这样的输出:

x~y
x~z
y~x
y~z

但我想要这样的输出:

x~y,z
y~x,z

这是我的 Python 代码:

allfields=['x','y','z'];
requiredfields=['x','y']
for rf in requiredfields:  
    for af in allfields:
        if rf not in af:
            txt=(rf+" ~ "+af)
            print(txt)

您可以在打印之前join allfields的值:

for rf in requiredfields:
    txt = rf + "~" + ",".join(a for a in allfields if a not in rf)
    print(txt)

当然,您也可以使用 join 来折叠外部循环:

print("n".join(rf + "~" + ",".join(a for a in allfields if a not in rf) 
for rf in requiredfields))

最新更新