有没有办法可以优雅地将函数输入转换为列表?在确保输入已经是列表的同时,将其保存在顶级列表中?
例如:
def pprint(input):
for i in input:
print(i)
a = ['Hey!']
pprint(a) # >>>>'Hey!'
b = 'Hey!'
pprint(b) # >>>> 'H', 'e', 'y', '!' # NOT WANTED BEHAVIOR
我目前的解决方法是进行类型检查,这既不是 Python 风格,也不是优雅的。有更好的解决方案吗?
# possible solution 1
def pprint2(input):
if type(input) not in [list, tuple]:
input = [input]
for i in input:
print(i)
# possible solution 2
# but I would really really like to keep the argument named! (because I have other named arguments in my actual function), but it does have the correct functionality!
def pprint3(*args):
for i in input:
print(i)