我试图仅返回字符串列表中出现的单个字符。所以下面的代码
words = ['man','map','human']
[letter for word in words for letter in word]
给出这个输出:
['m', 'a', 'n', 'm', 'a', 'p', 'h', 'u', 'm', 'a', 'n']
当我使用 set()
方法时,输出与我想要的完全一样,如下所示
words = ['man','map','human']
set([letter for word in words for letter in word ])
输出:
{'a', 'h', 'm', 'n', 'p', 'u'}
但是我试图解决的问题的说明要求我不使用集合。有人可以帮助提供替代方法来获得所需的输出吗?感谢您的宝贵时间。
最佳答案
使用生成器表达式,您不需要创建中间字母列表:
words = ['man','map','human']
res = []
for letter in (letter for word in words for letter in word):
if letter not in res:
res.append(letter)
现在:
>>> res
['m', 'a', 'n', 'p', 'h', 'u']
这相当于嵌套循环:
res = []
for word in words:
for letter in word:
if letter not in res:
res.append(letter)
关于python - 仅返回字符串的单个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36520284/