【问题标题】:List of formatted strings based on the elements of two lists基于两个列表元素的格式化字符串列表
【发布时间】:2018-01-27 07:32:16
【问题描述】:

我正在尝试在 Python 2.7 中以这种方式加入两个列表:

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

最终结果应该是:

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

我该怎么做?

【问题讨论】:

  • 您应该阅读一些文档并在询问之前自己尝试一下。这是基本的。
  • 我认为我不需要建议发布什么。

标签: python string python-2.7 list


【解决方案1】:
c = [p + str(q) for p, q in zip(a, b)]

【讨论】:

  • 感谢您的快速回复。
【解决方案2】:

与其串联字符串,不如使用string.format 函数。您还可以将其与 itertools.starmapzip 版本的列表一起使用:

>>> 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']

【讨论】:

  • 我也更喜欢format。它甚至使使用地图变得更好。结帐import itertools; itertools.starmap("{}{}".format, zip(a, b))
  • @juanpa.arrivillaga starmap 的好用例。
  • 非常感谢您详细而快速的回答。问题是我的清单很长。它在两个列表中都有 7000 项。当我使用你提出的方法时,它完美地做到了,但只有一半的项目。您知道会出现什么问题吗?
  • @SavasAdiloglu 可能您的列表之一的项目比另一个列表少。尝试使用 len(your_list) 检查两者的长度
  • 使用itertools.zip_longestfillvalue = '' 代替zip 有任何负面影响吗?
【解决方案3】:

您也可以尝试这个,基于@SilverSlash 的解决方案,使用map 函数:

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

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

输出:

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

【讨论】:

  • 也可以简化为list(map(''.join, zip(a, map(str, b))))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多