在Python中格式化print语句

时间:2014-12-05 23:42:31

标签: python output

我有一个脚本,它接收一个txt文件,其中包含作为程序输入的属性列表。对于每个属性,如果满足脚本的条件,它将打印出属性名称。但是,每个属性可能会多次满足,输出会多次打印。我现在想这样做:

condition 1 satisfied by A,B,C,D
condition 2 satisfied by A,B
condition 3 satisfied by B,D

我该怎么做? 我当前的输出看起来像

A
A
condition 3 not satisfied by A
B
B
B
condition 1 not satisfied by C
condition 2 not satisfied by C
C
D
condition 2 not satisfied by D
D

1 个答案:

答案 0 :(得分:0)

如何(在伪python代码中)

import collections
result = collections.defaultdict(list)
for attr in [A, B, C, D]:
  for cond in [condition1, condition2, ...]:
     if attr satisfies cond:
        result[cond].append(attr)

print result

输出:

{cond1: [A, B], cond2: [A], cond3: [C,D], ...}

我不确定这是你想要的。您没有明确(足够)说出您的输入是什么以及您想要输出的内容。