【问题标题】:Python: Join, Strings, Iterables, and DWIMPython:连接、字符串、迭代和 DWIM
【发布时间】:2018-07-25 08:21:53
【问题描述】:

应该joinDWIM(按我的意思做),还是有太多可能性,我应该继续进行所有检查?

我的结果可以是单个整数、整数列表、字符串或字符串列表。看来我必须将结果编组为一个字符串化元素列表,只是为了将一个可迭代对象传递给join。出于显而易见的原因,我也不希望将单个字符串拆分为字符。

以下是解释器中的一些尝试:

%> python
Python 3.6.0 (default, Dec 11 2017, 16:14:47) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 0
>>> ','.join(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only join an iterable
>>> x = [0, 1]
>>> ','.join(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found
>>> ','.join(map(str,x))
'0,1'
>>> x = 0
>>> ','.join(map(str,x))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> if not isinstance(x, (list, tuple)):
...     x = [x]
... 
>>> ','.join(map(str, x))
'0'
>>> x = [0, 1]
>>> ','.join(map(str, x))
'0,1'

所以看起来最好的办法是最后几位,即:

if not isinstance(x, (list, tuple)):
    x = [x]
joined = ','.join(map(str,x))

我正在寻找一种更好的方法来做到这一点,或者如果这是最好的方法,我会对此进行改进。

[对 Perl 喋喋不休地走开……]

【问题讨论】:

  • 更好是什么意思?不那么冗长?这对我来说看起来很简单。
  • 我不认为join 应该抛出异常,因为某些东西是不可迭代的。它应该只返回未触及的值,就像它对 0 或 1 个元素的列表一样。 (我可以克服转换为字符串的问题,因为这是一种语言设计选择,并且在大多数语言中都很常见。)
  • 在进一步的修改中,join 似乎对裸字符串(我忽略了检查)非常满意。 map 似乎不喜欢它。 map(print,0) 抱怨 0 不可迭代。
  • @jpp:当然,完成。但是这里的根本问题是裸整数是不可迭代的(但我认为应该是),而空列表是可迭代的,但我可以提出类似的论点,它不应该是。

标签: python list dictionary join iterable


【解决方案1】:

你所拥有的还不错。我能想到的只是明确检查可迭代并使用三元语句。换句话说,只有在你有一个可迭代对象时才使用join

from collections import Iterable

joined = str(x) if not isinstance(x, Iterable) else ','.join(map(str, x))

【讨论】:

  • Nitpick:hasattr(type(x), '__iter__') 是否可以在任何地方使用? (或者也许它只对字符串不起作用,这可能是我想要的。)
猜你喜欢
  • 2013-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-29
相关资源
最近更新 更多