打印 Python 中的字典列表
Print a list of lists of dicts in Python
我有以下字典列表:
l = [[{'close': 'TRUE'}], [{'error': 'FALSE'}], [{'close': 'TRUE', 'error': 'TRUE'}, {'close': 'TRUE', 'error': 'FALSE'}]]
我想这样打印:
(close = TRUE) & (error = FALSE) & ((close = TRUE & error = TRUE) | (close = TRUE & error = FALSE))
目前,我有以下功能几乎可以完成工作:
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)
但它给了我:
((close = TRUE)) & ((error = FALSE)) & ((close = TRUE & error = TRUE) | (close = TRUE & error = FALSE))
请注意“(close = TRUE)”和“(error = FALSE)”周围的额外括号。
如何删除这些?
只需使用 if
语句根据内部列表的长度更改格式字符串 (('({0})' if len(disjuncts) > 1 else '{0}')
)。像这样:
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))
我有以下字典列表:
l = [[{'close': 'TRUE'}], [{'error': 'FALSE'}], [{'close': 'TRUE', 'error': 'TRUE'}, {'close': 'TRUE', 'error': 'FALSE'}]]
我想这样打印:
(close = TRUE) & (error = FALSE) & ((close = TRUE & error = TRUE) | (close = TRUE & error = FALSE))
目前,我有以下功能几乎可以完成工作:
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)
但它给了我:
((close = TRUE)) & ((error = FALSE)) & ((close = TRUE & error = TRUE) | (close = TRUE & error = FALSE))
请注意“(close = TRUE)”和“(error = FALSE)”周围的额外括号。
如何删除这些?
只需使用 if
语句根据内部列表的长度更改格式字符串 (('({0})' if len(disjuncts) > 1 else '{0}')
)。像这样:
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))