我想要的映射函数的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):
???
答案 0 :(得分:1)
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)))
假设我正确理解你的问题
答案 1 :(得分:0)
我认为你真正追求的是相当于Ruby的“将它包装在数组中,如果它不是一个”运算符。 Python认为这不足以将其构建为语言语法。你可以很容易地自己定义它:
def tolist(thing):
return thing if isinstance(thing, list) else [thing]
def first_or_only(thing):
return tolist(thing)[0]