Python强制输入为列表
是否有一种方法可以优雅地将函数输入转换为列表?在确保输入已经是列表的同时,是否将其保留在顶级列表中 例如:Python强制输入为列表,python,list,Python,List,是否有一种方法可以优雅地将函数输入转换为列表?在确保输入已经是列表的同时,是否将其保留在顶级列表中 例如: def pprint(input): for i in input: print(i) a = ['Hey!'] pprint(a) # >>>>'Hey!' b = 'Hey!' pprint(b) # >>>> 'H', 'e', 'y', '!' # NOT WANTED BEHAVIOR 我目前的解决方
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)
使用
isinstance
和集合。Iterable
:
from collections import Iterable
def my_print(inp):
#As suggested by @user2357112
if not isinstance(inp, Iterable) or isinstance(inp, basestring):
inp = [inp] #use just `str` in py3.x
for item in inp: #use `yield from inp` in py3.x
yield item
...
>>> for x in my_print('foo'):
... print x
...
foo
>>> for x in my_print(range(3)):
print x
...
0
1
2
>>> for x in my_print(dict.fromkeys('abcd')):
print x
...
a
c
b
d
请注意,
pprint
是python中标准模块的名称,所以我建议您使用不同的变量名。使用assert和isinstance
>>> inp = "String to test"
>>> try:
... assert not isinstance(inp, basestring)
... for i in inp:
... print i
... except AssertionError:
... print inp
...
String to test
Python不能很好地进行类型检查。。。它打破了泛型系统。您真正想做什么?问题的可能重复与上述实现类似(或相同)。[中选择的答案是我所需要的。但是,我添加了@hcwhsa中的元素,因为我更喜欢他使用isinstance和iterable的检查。括号很混乱。我建议
不要使用isinstance(inp,iterable)或isinstance(inp,basestring)
断言不应用于控制流