Python:连接、字符串、可迭代对象和 DWIM
Python: Join, Strings, Iterables, and DWIM
应该join
DWIM(Do What I Mean),还是有太多可能性,我应该继续进行所有检查?
我的结果可以是单个整数、整数列表、字符串或字符串列表。看来我必须将结果编组到一个字符串化元素列表中,只是为了将一个可迭代对象传递给 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
。
from collections import Iterable
joined = str(x) if not isinstance(x, Iterable) else ','.join(map(str, x))
应该join
DWIM(Do What I Mean),还是有太多可能性,我应该继续进行所有检查?
我的结果可以是单个整数、整数列表、字符串或字符串列表。看来我必须将结果编组到一个字符串化元素列表中,只是为了将一个可迭代对象传递给 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
。
from collections import Iterable
joined = str(x) if not isinstance(x, Iterable) else ','.join(map(str, x))