0

假设我有以下 python 代码:

hp = 0
if 'header' is in paramdict.keys():
    hp = paramdict['header']
mydf = [pd.read_excel(xlsx, sheet, header = hp) for sheet in xlsx.sheet_names]

我只想通过header,如果它在paramdict。(默认值为 0)

有没有更好的方法来做到这一点,或者一种更容易眼睛/占用更少空间的方法?我已经尝试过 fstrings 和 eval 但无法让它们工作。

4

1 回答 1

2

dict有一个.get方法允许你传递一个默认值,如果key存在dict

hp = paramdict.get('header', 0)
mydf = [pd.read_excel(xlsx, sheet, header=hp) for sheet in xlsx.sheet_names]

这是一个例子,

>>> d = {'one': 1, 'two': 2}
>>> d
{'one': 1, 'two': 2}
>>> d.get('one', 'Nope, not here')
1
>>> d.get('three', 'Nope, not here')
'Nope, not here'
于 2020-07-08T16:32:55.793 回答