python - 仅返回字符串的单个匹配项

标签 python

我试图仅返回字符串列表中出现的单个字符。所以下面的代码

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/

相关文章:

Python - struct.pack 与 Strike.packinto

python - 以编程方式指定 Django 模型属性

java - 从一系列随机字母中找到单词?

python - 如何嵌套两个具有相同模型的序列化器

python - 多源服务器简单开发http-proxy

python - Scrapy 的最佳性能

python - 查找最佳子字符串匹配

python - 使用 Django-storages 删除 Amazon S3 中的文件

python - 无法在 OS X 10.10 Yosemite 上安装 Python-MySQL

python - pd.read_excel ("file.xlsx")不会创建 'DataFrame' 而是 'OrderedDict'