收集字符串列表中字符的位置

2024-04-18 20:23:20 发布

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

如果我有一个字符串列表,并且我想收集字符串中每个字符的位置,那么最好的方法是什么?例如,如果我有一个列表:

text = []
stopword = ""
while True:
    line = raw_input()
    if line.strip() == stopword:
        break
    text.append(line)

text = ['fda', 'adf', 'esf', 'esfe']

我想创造出这样的东西:

 newlst = ['faee', 'ddss', 'afff', 'e']

有简单的方法吗?我正在创建大量的for循环,看起来很复杂。你知道吗


Tags: 方法字符串texttrue列表inputrawif
1条回答
网友
1楼 · 发布于 2024-04-18 20:23:20

您可以使用^{} from ^{}*:

>>> from itertools import izip_longest
>>> text = ['fda', 'adf', 'esf', 'esfe']
>>> map(''.join, izip_longest(*text, fillvalue=''))
['faee', 'ddss', 'afff', 'e']

这将在每个位置创建字符元组的迭代器:

>>> list(izip_longest(*text, fillvalue=''))
[('f', 'a', 'e', 'e'), ('d', 'd', 's', 's'), ('a', 'f', 'f', 'f'), ('', '', '', 'e')]

然后使用^{}^{}将元组转换回字符串。如果*语法不熟悉,请参见What does ** (double star) and * (star) do for parameters?


*如果使用Python3.x,请注意此函数已重命名为zip_longest,因为zip现在采用迭代器行为,并且izip不再存在-请参见例如What's New in Python 3.0

相关问题 更多 >