【问题标题】:Pythonic way to check if a function input is a list or string [duplicate]检查函数输入是列表还是字符串的Pythonic方法[重复]
【发布时间】:2019-03-05 10:39:48
【问题描述】:

我想知道最pythonic 的方法是检查函数输入是字符串还是列表。我希望用户能够输入字符串列表或字符串本身。

def example(input):

   for string in input:

       #Do something here.
       print(string)

显然,这将在输入是字符串列表时起作用,但如果输入是单个字符串则不起作用。最好的办法是在函数本身中添加类型检查吗?

def example(input):

    if isinstance(input,list):
       for string in input:
           print(input)
           #do something with strings
    else:
        print(input)
        #do something with the single string

谢谢。

【问题讨论】:

  • 那么你的第二种方法有什么问题?
  • 你的第二种方法似乎没问题。
  • 第二种方法是我会怎么做。
  • 像这样可以接受不同类型的多态函数的用例很少见,但你所做的很好
  • 第二种方法没有问题,我只是想知道它是否是处理这类问题的最佳方式。

标签: python pep


【解决方案1】:

第二种方法很好,除了它应该使用print(string_) 而不是print(input),如果重要的话:

def example(input):
    if isinstance(input,list):
       for string_ in input:
           print(string_)
           #do something with strings
    else:
        print(input)
        #do something with the single string


example(['2','3','4'])
example('HawasKaPujaari')

输出:

2
3
4
HawasKaPujaari

【讨论】:

  • 对不起,这是正确的,这是我原始代码中的错字。只要列表的这种类型检查被认为是正确的风格,我就很高兴了。
【解决方案2】:

您的代码很好。但是您提到列表应该是字符串列表:

if isinstance(some_object, str):
    ...
elif all(isinstance(item, str) for item in some_object): # check iterable for stringness of all items. Will raise TypeError if some_object is not iterable
    ...
else:
    raise TypeError # or something along that line

Check if input is a list/tuple of strings or a single string

【讨论】:

  • 这比 OP 的第二种方法好多少?
  • 忘了告诉他的代码没问题。但是他提到列表应该是字符串列表。
  • 你应该在代码中添加这么多检查吗?
  • 这取决于你,如果你有必要检查列表是否真的是字符串列表,是的,肯定的。如果您以某种方式确定它是,它只会成为几乎无用的双重检查。
猜你喜欢
  • 1970-01-01
  • 2010-10-29
  • 2022-09-25
  • 2021-10-16
  • 2013-10-09
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多