[英]Print a list of lists of dicts in Python
I have the following list of lists of dicts: 我有以下词典列表:
l = [[{'close': 'TRUE'}], [{'error': 'FALSE'}], [{'close': 'TRUE', 'error': 'TRUE'}, {'close': 'TRUE', 'error': 'FALSE'}]]
and I would like to print it this way: 我想这样打印:
(close = TRUE) & (error = FALSE) & ((close = TRUE & error = TRUE) | (close = TRUE & error = FALSE))
For the moment, I have the following function which nearly do the job: 目前,我具有以下功能几乎可以完成这项工作:
def pretty_string(l):
print ' & '.join('({0})'
.format(' | '
.join('({0})'
.format(' & '
.join('{0} = {1}'
.format(key, value)
for key, value
in disjuncts.items()))
for disjuncts
in conjuncts))
for conjuncts
in l)
But it gives me: 但这给了我:
((close = TRUE)) & ((error = FALSE)) & ((close = TRUE & error = TRUE) | (close = TRUE & error = FALSE))
Notice the extra parentheses around "(close = TRUE)" and "(error = FALSE)". 请注意“(close = TRUE)”和“(error = FALSE)”周围的多余括号。
How can these be removed? 如何删除这些?
Just use if
statement to change format string ( ('({0})' if len(disjuncts) > 1 else '{0}')
) depending on the length of your internal list. 只需根据内部列表的长度使用
if
语句更改格式字符串( ('({0})' if len(disjuncts) > 1 else '{0}')
,则更改格式字符串( ('({0})' if len(disjuncts) > 1 else '{0}')
。 Like this: 像这样:
def pretty_string(l):
print ' & '.join(
'({0})'.format(
' | '.join(
('({0})' if len(disjuncts) > 1 else '{0}').format(
' & '.join(
'{0} = {1}'.format(key, value) for key, value in disjuncts.items()
)
) for disjuncts in conjuncts
)
) for conjuncts in l
)
def conv(item):
if(isinstance(item, dict)):
yield '(' + ' & '.join("{} = {}".format(*i) for i in item.items()) + ')'
elif(isinstance(item, list)):
for i in item:
for s in conv(i):
yield s
def pretty_string(l):
return ' | '.join(conv(l))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.