与其串联字符串,不如使用string.format 函数。您还可以将其与 itertools.starmap 和 zip 版本的列表一起使用:
>>> from itertools import starmap
>>> a = ['x','y','z']
>>> b = [1,2,3]
>>> list(starmap("{}{}".format, zip(a, b)))
['x1', 'y2', 'z3']
# Note: `starmap` returns an iterator. If you want to iterate this value
# only once, then there is no need to type-case it to `list`
或者你可以将它与传说中的列表推导一起使用:
>>> ['{}{}'.format(x, y) for x, y in zip(a, b)]
['x1', 'y2', 'z3']
使用format,您不必将int 显式类型转换为str。此外,更改列表中所需字符串的格式也更简单。例如:
>>> ['{} -- {}'.format(x, y) for x, y in zip(a, b)]
['x -- 1', 'y -- 2', 'z -- 3']
这是一个格式化n列表的通用解决方案:
>>> my_lists = [
['a', 'b', 'c'], # List 1
[1, 2, 3], # List 2
# ... # few more lists
['x', 'y', 'z'] # List `N`
]
# Using `itertools.starmap`
>>> list(starmap(("{}"*len(my_lists)).format, zip(*my_lists)))
['a1x', 'b2y', 'c3z']
# Using list comprehension
>>> [('{}'*len(my_lists)).format(*x) for x in zip(*my_lists)]
['a1x', 'b2y', 'c3z']