【问题标题】:Print a list of lists of dicts in Python在 Python 中打印字典列表的列表
【发布时间】:2015-07-23 13:10:13
【问题描述】:

我有以下字典列表:

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)”周围的额外括号。

如何删除这些?

【问题讨论】:

    标签: python string list dictionary set


    【解决方案1】:

    只需使用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
        )
    

    【讨论】:

      【解决方案2】:
      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))
      

      【讨论】:

        猜你喜欢
        • 2013-02-16
        • 2022-08-19
        • 2017-08-20
        • 2016-11-26
        • 2015-10-03
        • 1970-01-01
        • 1970-01-01
        • 2023-01-03
        • 1970-01-01
        相关资源
        最近更新 更多