python如何为配置文件中的单个键分配2个逗号分隔值

时间:2017-12-29 08:15:25

标签: python-3.x list anaconda

我有这样的输出:

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)

1 个答案:

答案 0 :(得分:2)

在打印之前,您可以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))