Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如果传递的是列表中的第一个字符串,或者是字符串本身,而不是列表,那么如何返回该字符串?_Python_Splat - Fatal编程技术网

Python 如果传递的是列表中的第一个字符串,或者是字符串本身,而不是列表,那么如何返回该字符串?

Python 如果传递的是列表中的第一个字符串,或者是字符串本身,而不是列表,那么如何返回该字符串?,python,splat,Python,Splat,我想要的映射函数的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"] =&

我想要的映射函数的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):
    ???
定义f(某物): 如果isinstance(某物,基串): 归还某物 elif isinstance(某物,(列表,元组)): 返回某物[0] 引发异常(“未知内容:%s”%(内容,键入(内容)))
假设我正确理解了你的问题,我想你真正想要的是Ruby的“如果不是一个,就把它包装在一个数组中”操作符。Python认为这不够重要,无法将其构建到语言语法中。您可以很容易地自己定义它:

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

def first_or_only(thing):
    return tolist(thing)[0]

为什么一根绳子不能用呢?您如何有资格将其视为设计失败?请用通俗易懂的英语说明您期望的输入和输出是什么?@Sukrikara即使错误,您也不应编辑代码,除非重新格式化、调整白色字符或注释等。@JoranBeasley,期望的输入和输出在问题标题中。设计失败体现在对Ruby代码的演示和一个事实上,我不知道如何在Python中实现同样的优雅。你说,因为你不知道如何在Python中做一些事情,Python有一个设计缺陷?@Nakilon他们否决了你,因为你不小心责备了Python。我会帮你修改你的英语,但是Python实际上有splat操作符。我不明白为什么它不一样强大。如果事物是一个元组或另一个iterable,它就不起作用了…@septi:确实不会。这就是Python没有这个操作符的原因之一。
def tolist(thing):
    return thing if isinstance(thing, list) else [thing]

def first_or_only(thing):
    return tolist(thing)[0]