Skip to main content
 首页 » 编程设计

python之以相同方式处理列表和字典之默认情况下

2025年05月04日11yxwkf

我有一个函数可以与 list 和 dict 一起使用:

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

并且如果 row 是一个 list 那么 md.first 和 md.next 将是 ints,如果 row 是 dict,它们将是 strings。

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

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

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

当然可以

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/简洁的方法来做到这一点?

请您参考如下方法:

按照 this question 中的描述编写一个“安全查找”函数并用它来进行查找。了解 LookupError 是 KeyError 和 ValueError 的父类(super class)很有用,因此您可以捕获列表或列表中缺失的索引通过捕获 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)