如何从列表或字符串本身返回第一个字符串(如果它是传递的而不是列表)



我想要的映射函数的Ruby示例:

["qwe", ["asd", "zxc"]].map{ |i| [*i][0] } => ["qwe", "asd"]
def f array_or_string
  [*array_or_string].first
end
["qwe", ["asd", "zxc"]].map &method(:f)    => ["qwe", "asd"]
f ["qwe", "zxc"]                           => "qwe"
f "asd"                                    => "asd"

由于字符串在 Python 中是可迭代的,我该如何应对这种语言设计失败优雅地达到相同的结果?

def f(array_or_string):
    ???
def f(something):
    if isinstance(something,basestring): 
         return something
    elif isinstance(something,(list,tuple)):
         return something[0]
    raise Exception("Unknwon Something:%s <%s>"%(something,type(something)))

假设我正确理解了您的问题

我认为你真正追求的是 Ruby 的"如果它不是一个,则将其包装在数组中"运算符。Python认为这不够重要,无法将其构建到语言语法中。您可以自己轻松定义它:

def tolist(thing):
    return thing if isinstance(thing, list) else [thing]
def first_or_only(thing):
    return tolist(thing)[0]

最新更新