将两个列表组合成字符串

2024-05-20 00:54:50 发布

您现在位置:Python中文网/ 问答频道 /正文

实际上,我试图将两个列表合并为一个字符串,但保持它们的顺序意味着:

list1 = [1,2,3,4,5]
list2 = ["one", "two", "three", "four", "five"]

result = "1one2two3three4four5five"

(列表的长度始终相同,但内容不同)

目前我是这样做的:

result = ""
i = 0

for entry in list1:
    result += entry + list2[i]
    i += 1

我想一定有一个更像Python的方法来做这个,但我不知道实际上。

希望你们中有人能帮我解决这个问题。


Tags: 字符串in内容列表for顺序resultone
3条回答

string formattingstr.join()zip()一起使用:

>>> list1 = [1,2,3,4,5]
>>> list2 = ["one", "two", "three", "four", "five"]

>>> "".join("{0}{1}".format(x,y) for x,y in zip(list1,list2))
'1one2two3three4four5five'

zip(list1,list2)返回如下内容: [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')]

现在,对于这个列表中的每一项,我们应用字符串格式,然后使用str.join()连接整个生成器表达式。

list1 = [1,2,3,4,5]
list2 = ["one", "two", "three", "four", "five"]

print ''.join([str(a) + b for a,b in zip(list1,list2)])
1one2two3three4four5five
>>> import itertools
>>> ''.join(map(str, itertools.chain.from_iterable(zip(list1, list2))))
1one2two3three4four5five'

说明:

  • zip(list1, list2)创建一个列表,其中包含两个列表中匹配元素的元组:

    >>> zip(list1, list2)
    [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')]
    
  • ^{}展开嵌套列表:

    >>> list(chain.from_iterable(zip(list1, list2)))
    [1, 'one', 2, 'two', 3, 'three', 4, 'four', 5, 'five']
    
  • 现在我们需要确保只有字符串,所以我们使用map()str()应用于所有项

  • 最后''.join(...)将列表项合并为一个不带分隔符的字符串。

相关问题 更多 >