Say I have a list of three words and I want to generate a list containing the characters in the word.
This can be achieved easily using for-loops or list-comprehension:
wordList = ["one", "two", "three"]
letterList = []
# Solution 1:
for word in wordList:
for letter in word:
letterList.append(letter)
# Solution 2:
letterList = [letter for word in wordList for letter in word]
print(letterList) # Prints: ['o', 'n', 'e', 't', 'w', 'o', 't', 'h', 'r', 'e', 'e']
However, when this problem is made more difficult, I am unable to find a solution using a list-comprehension.
For example, assume I want to generate the previous list, but I also want any duplicate characters to be removed.
I can do this using for-loops:
wordList = ["one", "two", "three"]
letterList = []
for word in wordList:
for letter in word:
if letter not in letterList:
letterList.append(letter)
print(letterList) # Prints: ['o', 'n', 'e', 't', 'w', 'h', 'r']
So, my question is: How do I check to see if an item is in the list being build during a list comprehension? Or put more simply: How do I do the above using list-comprehensions?
In Python 3.6 dictionaries are ordered. Therefore you can use a dict comprehension:
>>> list({letter:None for word in wordList for letter in word}.keys())
['o', 'n', 'e', 't', 'w', 'h', 'r']
Starting from Python 3.7 the ordering will be guaranteed:
python news: 😀 @gvanrossum just pronounced that dicts are now guaranteed to retain insertion order. This is the end of a long journey. source (2017-12-15)
if order is not important just use a set comprehension
letter_set = {letter for word in wordList for letter in word}
if order is important it gets a bit grosser
seen = set()
letter_list = [x for word in wordlist for x in word if x not in seen and not seen.add(s)]
or using something like ordered dict
from collections import OrderedDict
my_list = OrderedDict.fromkeys(letter for word in wordList for letter in word).keys()
You already got the set solution but here is one different solution :
Instead of using that list comprehension result , use that list comprehension for logic and append it to new list :
wordList = ["one", "two", "three"]
letterList = []
[letterList.append(letter) for word in wordList for letter in word if letter not in letterList]
print(letterList)
output:
['o', 'n', 'e', 't', 'w', 'h', 'r']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.