【问题标题】:Handling lists and dicts identically - with default以相同方式处理列表和字典 - 使用默认值
【发布时间】:2016-02-19 19:57:33
【问题描述】:

我有一个函数可以同时使用lists 和dicts:

def row2tuple (row, md):
    return (row[md.first], row[md.next])

如果rowlist,那么md.firstmd.next 将是ints,如果rowdict,它们将是strings。

但是,如果 rowdict 并且缺少字段,则会导致错误。如果我使用get 方法:

def row2tuple (row, md):
    return (row.get(md.first), row.get(md.next))

它完全符合我对dicts 的要求,但它对lists 根本不起作用。

当然可以

def row2tuple (row, md):
    if isinstance(row,list):
        return (row[md.first], row[md.next])
    return (row.get(md.first), row.get(md.next))

但它看起来很丑。

有没有更 Pythonic/简洁的方法来做到这一点?

【问题讨论】:

  • 您在第二种方法中没有将任何内容转换为int
  • 您是否还要处理用户确实传递了一个整数,但该整数超出了列表范围的情况?对于您的最后一个示例(使用get),这仍然会引发错误。
  • @Kasramvd:是的,索引应该是每次解析的
  • @BrenBarn:不,我确实希望在这种情况下出错。

标签: python python-2.7


【解决方案1】:

按照this question 中的描述编写一个“安全查找”函数并使用它进行查找。知道LookupErrorKeyErrorValueError 的超类很有用,因此您可以通过捕获LookupError 来捕获列表或字典中缺失的索引:

def safeLookup(container, index):
    try:
        return container[index]
    except LookupError:
        return None

def makeTuple(container, indices):
    return tuple(safeLookup(container, index) for index in indices)

然后:

>>> makeTuple([1, 2, 3], [0, 2, 4])
(1, 3, None)
>>> makeTuple({'x': 1, 'y': 2, 'z': 3}, ['x', 'z', 'hoohah'])
(1, 3, None)

【讨论】:

    【解决方案2】:

    基于EAFP 方式,请求宽恕比请求许可更容易。因此,如果您确定您只是在处理这两种类型的对象(listdict)作为一种更 Python 的方式,您可以使用 try-except 表达式:

    def row2tuple (row, md):
        try:
            return (row[md.first], row[md.next])
        except TypeError:
            return (row.get(md.first), row.get(md.next))
    

    【讨论】:

      【解决方案3】:

      我认为你所拥有的很好,但如果你喜欢这里是一个(永远如此)更简洁的选择:

      def row2tuple (row, md):
          method = row.__getitem__ if isinstance(row,list) else row.get
          return (method(md.first), method(md.next))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-14
        • 2019-09-06
        • 2016-05-10
        相关资源
        最近更新 更多