English 中文(简体)
采用“如果”理解的清单编制一个无重复的项目清单
原标题:Using a list comprehension with "if" to create a list of items without duplication

I have a list word_list = [ cat , dog , rabbit ]. I want to use list comprehension to print each individual character from the list but removes any duplicate character. This is my code:

word_list = [ cat ,  dog ,  rabbit ]
letter_list = [""]
letter_list = [letter for word in word_list for letter in word if letter not in letter_list ]
print(letter_list)

这一收益代码[c、a、t、d、o、g、 r、a、b、b、i、t]/code,不是预期结果的<代码>[c、a、t、d、o、 g、 r、b、i]/code,我可以说明原因。

最佳回答

如果允许一些变数的初始化,在技术上可以采用清单理解的复制方法。

您可使用一套<代码>seen,以跟踪已碰到的信函,并使用一套<代码>include,以记录本信是否已在插入“<>seen/code>之前即已见到:

seen = set()
include = set()
print([
    letter for word in word_list for letter in word
    if (
        include.clear() if letter in seen else include.add(1),
        seen.add(letter)
    ) and include
])

因为3.8 ,你也可以使用派任表达方式,避免依赖职能附带影响,而职能一般在一份清单中受到抑制:

seen = set()
print([
    letter for word in word_list for letter in word
    if (
        include := letter not in seen,
        seen := seen | {letter}
    ) and include
])

但是,如果你在执行与清单核对表有关的复制时没有死亡,那么使用<编码>dict. fromkeys就会更清洁。 相反,由于关键词总是独一无二,继第3.7号决议以来插入令之后:

from itertools import chain
print([*{}.fromkeys(chain(*word_list))])

∗ E/CN.6/2009/1。 在线查询!

问题回答

您可以通过一份清单理解来做到这一点,因为letter not in letter_list 系指letter_list/code>的原始价值。 由于<代码>字母_list=的转让在清单完成之前就没有发生。

使用普通<条码> 顺便提一下,你可以随行更新。

letter_list = []
for word in word_list:
    for letter in word:
        if letter not in letter_list:
            letter_list.append(letter)

请参看letter_list ,从名单上删除。 在清单理解之前,即[”],你可以使用一套清单。

letter_list = {letter for word in word_list for letter in word}

这尤其给与独特的信函。

具体来说,这份清单并不与核对清单相同。

word_list = [ cat ,  dog ,  rabbit ]
letter_list = [""]
for word in word_list:
    for letter in word:
        if letter not in letter_list:
            letter_list.append(letter)

等同

word_list = [ cat ,  dog ,  rabbit ]
letter_list = [""]

temp_letter_list = [""]
for word in word_list:
    for letter in word:
        if letter not in letter_list:
            temp_letter_list.append(letter)
letter_list = temp_letter_list

注 采用临时名单作为理解清单。

如果您希望有一个清单而不是一个清单,则使用<代码>list(字母_list),如果您希望使用<代码>(字母_list)。

名单完全乐于重复。 因此,列出其中的内容。

word_list = [ cat ,  dog ,  rabbit ]
letter_list = list({letter for word in word_list for letter in word})
print(letter_list)

您实际上能够用所有清单打造阵列,最后把它作为一组,以便删除名单上的每封信件。

word_list = [ cat ,  dog ,  rabbit ]
letter_list = [letter for word in word_list for letter in word]
print(list(set(letter_list))) 

myList = [ ],右边的完整清单是在分配变量之前编制的,这样你就可以在理解中看到新的内容。

但是,如果你使用延期办法,即预期可以调用的参数,则可调取的每一项目都会随着时间的推移而增加,因此,你的谅解将使人们了解增加的项目。

这与你已经掌握的方法非常接近:

word_list = [ cat ,  dog ,  rabbit ]

letter_list = []
letter_list.extend(letter  for word   in word_list 
                           for letter in word if letter not in letter_list)

print(letter_list)
[ c ,  a ,  t ,  d ,  o ,  g ,  r ,  b ,  i ] 

更有效的办法是使用字典,确保信函是独一无二的(同时保持原有次序):

word_list = [ cat ,  dog ,  rabbit ]

*letter_list, = dict.fromkeys(letter for word in word_list for letter in word)

print(letter_list)
[ c ,  a ,  t ,  d ,  o ,  g ,  r ,  b ,  i ] 




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签