与defau相同的处理列表和命令

2024-10-01 15:31:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,它应该同时与listdict一起工作:

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

如果rowlist,那么md.firstmd.next将是int,如果rowdict,它们将是str

但是,如果rowdict并且缺少字段,则会导致错误。如果我使用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))

但看起来很难看

有没有更简洁的方法


Tags: 方法函数getreturndef错误mddict
3条回答

基于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))

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

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)

我认为你所拥有的一切都是好的,但如果你喜欢,这里有一个更简洁的选择:

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

相关问题 更多 >

    热门问题