这些答案都不能推广到 R 中的 paste 那样的任意数量的参数。这是原始 R 函数的一个相当忠实的移植。唯一要记住的是每个元素都必须以列表的形式呈现,因为 R 中的字符串实际上只是引擎盖下的字符向量:
import itertools
def paste(*args, sep = ' ', collapse = None):
"""
Port of paste from R
Args:
*args: lists to be combined
sep: a string to separate the terms
collapse: an optional string to separate the results
Returns:
A list of combined results or a string of combined results if collapse is not None
"""
combs = list(itertools.product(*args))
out = [sep.join(str(j) for j in i) for i in combs]
if collapse is not None:
out = collapse.join(out)
return out
用法:
paste (['s'], range(10), sep = '')
Out[62]: ['s0', 's1', 's2', 's3', 's4', 's5', 's6', 's7', 's8', 's9']
paste (['s'], range(2), ['t'], range(3), sep = '')
Out[63]: ['s0t0', 's0t1', 's0t2', 's1t0', 's1t1', 's1t2']
paste (['s'], range(2), ['t'], range(3), sep = '', collapse = ':')
Out[64]: 's0t0:s0t1:s0t2:s1t0:s1t1:s1t2'
使用柯里化可以得到paste0:
from functools import partial
paste0 = partial(paste, sep = '')