Python:Join、Strings、Iterables和DWIM
是应该加入DWIM(按我的意思做),还是有太多的可能性,我应该继续做所有的检查 我有一个结果,可以是单个int、int列表、字符串或字符串列表。似乎我必须将结果整理成一个字符串化元素列表,只需将一个iterable传递给Python:Join、Strings、Iterables和DWIM,python,list,dictionary,join,iterable,Python,List,Dictionary,Join,Iterable,是应该加入DWIM(按我的意思做),还是有太多的可能性,我应该继续做所有的检查 我有一个结果,可以是单个int、int列表、字符串或字符串列表。似乎我必须将结果整理成一个字符串化元素列表,只需将一个iterable传递给join。出于显而易见的原因,我也不希望将单个字符串拆分为多个字符 以下是在解释器中的一些尝试: %> python Python 3.6.0 (default, Dec 11 2017, 16:14:47) [GCC 5.4.0 20160609] on linux T
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'
我正在寻找一个更好的方法来实现这一点,或者如果这是最好的方法的话,在这方面进行改进
[闲聊着谈论Perl…]你拥有的还不错。我所能想到的就是显式地检查iterable并使用三元语句。换句话说,只有当您有一个iterable时才使用
join
from collections import Iterable
joined = str(x) if not isinstance(x, Iterable) else ','.join(map(str, x))
你说的更好是什么意思?不那么冗长?我觉得这很简单。我不认为
join
应该抛出异常,因为有些东西不可测试。它应该只返回未触及的值,就像它对包含0或1个元素的列表所做的那样。(我可以克服转换为字符串的问题,因为这是一种语言设计选择,在大多数语言中都很常见。)进一步的修补,似乎join
对一个裸字符串(我忽略了检查)非常满意<代码>地图似乎不喜欢它<代码>地图(打印,0)抱怨0
不可编辑。@jpp:当然,完成。但这里的根本问题是裸整数不可iterable(但我认为应该是),而空列表是可iterable,但我可以提出一个类似的论点,它不应该是。吹毛求疵:hasattr(type(x),“\uuu iter”
在任何地方都有效吗?(或者它只对字符串不起作用,这可能就是我在这里想要的。)
from collections import Iterable
joined = str(x) if not isinstance(x, Iterable) else ','.join(map(str, x))