Python 仅返回字符串的单个匹配项
我试图只返回字符串列表中出现的单个字符。下面的代码Python 仅返回字符串的单个匹配项,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 = ['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'}
但我试图解决的问题的说明要求我不使用集合。是否有人能提供另一种方法来获得所需的输出。非常感谢您的时间。好吧,不使用
set
不是个好主意,但以防万一
list = ['m', 'a', 'n', 'm', 'a', 'p', 'h', 'u', 'm', 'a', 'n']
withoutduplicates = [(list[i]) for i in range (0,len(list)) if list[i] not in list[:i]]
print withoutduplicates
尝试:
它将输出:
['m', 'a', 'n', 'p', 'h', 'u']
如果要排序,将发出
['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 = []
for word in words:
for letter in word:
if letter not in res:
res.append(letter)
或者不理解:
def nodupes(l):
seen = []
for c in l:
if c not in seen:
seen.append(c)
return seen
nodupes(['m', 'a', 'n', 'm', 'a', 'p', 'h', 'u', 'm', 'a', 'n'])
你需要手动跟踪你看到的任何字母(因为你不能使用集合),我建议你不要直接跳转到理解。分解你的算法,一步一步地执行,看看解决问题后你可以在哪里进行优化。你能使用字典吗?@MikeMüller不应该使用字典见。
res = []
for word in words:
for letter in word:
if letter not in res:
res.append(letter)
def nodupes(l):
seen = []
for c in l:
if c not in seen:
seen.append(c)
return seen
nodupes(['m', 'a', 'n', 'm', 'a', 'p', 'h', 'u', 'm', 'a', 'n'])