简体   繁体   English

基于两个列表的元素的格式化字符串列表

[英]List of formatted strings based on the elements of two lists

I am trying to join two lists in such a manner in Python 2.7: 我试图在Python 2.7中以这种方式加入两个列表:

a = ['x','y','z']
b = [1,2,3]

and the end result should be: 最终结果应该是:

c=['x1','y2','z3']

How do I do that? 我怎么做?

c = [p + str(q) for p, q in zip(a, b)]

Instead of concatenating the string, it is even better to use string.format function. 与其串联字符串,不如使用string.format函数。 You can also use it with itertools.starmap with the zip version of the lists as: 您还可以将其与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`

Or you can use it with the legendary list comprehensions as: 或者,您也可以将其与传说中的列表推导结合使用:

>>> ['{}{}'.format(x, y) for x, y in zip(a, b)]
['x1', 'y2', 'z3']

With format , you don't have to explicitly type-cast your int to str . 使用format ,您不必显式将int类型转换为str Also it is simpler to change the format of your desired strings in the lists. 同样,在列表中更改所需字符串的格式也更​​简单。 For example: 例如:

>>> ['{} -- {}'.format(x, y) for x, y in zip(a, b)]
['x -- 1', 'y -- 2', 'z -- 3']

Here's a generalized solution to format n lists : 这是格式化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']

You can try this one as well, based on @SilverSlash's solution, using the map function: 您也可以使用map函数,基于@SilverSlash的解决方案尝试这种方法:

a = ['x','y','z']
b = [1,2,3]

c = list(map(''.join, zip(a, map(str, b))))
print(c)

Output: 输出:

['x1', 'y2', 'z3']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM