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

Python 收集字符串列表中字符的位置,python,list,sorting,count,Python,List,Sorting,Count,如果我有一个字符串列表,并且我想收集字符串中每个字符的位置,那么最好的方法是什么?例如,如果我有一个列表: text = [] stopword = "" while True: line = raw_input() if line.strip() == stopword: break text.append(line) text = ['fda', 'adf', 'esf', 'esfe'] 我想创造一些东西,比如: newlst = ['faee

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

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']
有简单的方法吗?我正在为循环创建大量的
,它看起来很复杂。

您可以使用*:

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

>>> list(izip_longest(*text, fillvalue=''))
[('f', 'a', 'e', 'e'), ('d', 'd', 's', 's'), ('a', 'f', 'f', 'f'), ('', '', '', 'e')]
然后使用和将元组转换回字符串。如果不熟悉
*
语法,请参阅


*如果使用Python 3.x,请注意此函数已重命名为
zip\u longest
,因为
zip
现在采用迭代器行为,并且
izip
不再存在-请参见例如..

您可以使用*:

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

>>> list(izip_longest(*text, fillvalue=''))
[('f', 'a', 'e', 'e'), ('d', 'd', 's', 's'), ('a', 'f', 'f', 'f'), ('', '', '', 'e')]
然后使用和将元组转换回字符串。如果不熟悉
*
语法,请参阅


*如果使用Python 3.x,请注意,此函数已重命名为
zip\u longest
,因为
zip
现在采用迭代器行为,并且
izip
不再存在-请参见示例