How to remove specific item from list? - python

I'm trying to remove spam from the given choices on the menu, my for loop doesn't work.
menu = [
["egg", "bacon"],
["egg", "sausage", "bacon"],
["egg", "spam"],
["egg", "bacon", "spam"],
["egg", "bacon", "sausage", "spam"],
["spam", "bacon", "sausage", "spam"],
["spam", "sausage", "spam", "bacon", "spam", "tomato",
"spam"],
["spam", "egg", "spam", "spam", "bacon", "spam"],
]
for choice in menu:
if "spam" in choice:
remove("spam")
print(choice)

As stated by #h4z4, remove is not defined. Try
for choice in menu:
if "spam" in choice:
choice.remove("spam")
print(choice)
However, remove only removes the first occurrence. To remove all occurrences, try:
for choice in menu:
if "spam" in choice:
choice = [item for item in choice if item != "spam"]
print(choice)

To remove all "spam" from sublists, use list-comprehension:
menu = [
["egg", "bacon"],
["egg", "sausage", "bacon"],
["egg", "spam"],
["egg", "bacon", "spam"],
["egg", "bacon", "sausage", "spam"],
["spam", "bacon", "sausage", "spam"],
["spam", "sausage", "spam", "bacon", "spam", "tomato", "spam"],
["spam", "egg", "spam", "spam", "bacon", "spam"],
]
menu = [[val for val in subl if val != "spam"] for subl in menu]
print(menu)
Prints:
[['egg', 'bacon'],
['egg', 'sausage', 'bacon'],
['egg'],
['egg', 'bacon'],
['egg', 'bacon', 'sausage'],
['bacon', 'sausage'],
['sausage', 'bacon', 'tomato'],
['egg', 'bacon']]

As already pointed out remove is a method of list and should be called as choice.remove("spam")
remove only removes the first occurrence of the element
Here is a way to do this with remove and count
Code:
menu = [
["egg", "bacon"],
["egg", "sausage", "bacon"],
["egg", "spam"],
["egg", "bacon", "spam"],
["egg", "bacon", "sausage", "spam"],
["spam", "bacon", "sausage", "spam"],
["spam", "sausage", "spam", "bacon", "spam", "tomato",
"spam"],
["spam", "egg", "spam", "spam", "bacon", "spam"],
]
for choice in menu:
c = choice.count('spam') # returns number of occurrences of 'spam' in choice
while c: # to remove spam from choice c times
choice.remove("spam")
c-=1
print(*menu, sep='\n')
Output:
['egg', 'bacon']
['egg', 'sausage', 'bacon']
['egg']
['egg', 'bacon']
['egg', 'bacon', 'sausage']
['bacon', 'sausage']
['sausage', 'bacon', 'tomato']
['egg', 'bacon']
But I would prefer list comprehension

Related

Python: Printing out list without certain item

I'm trying to iterate over a list and wanting print out every item except - spam.
But, I keep getting an error stating the following: Expected type 'list[str]' (matched generic type '_T) got 'str' instead.
menu = [
["egg", "bacon"],
["egg", "sausage", "bacon"],
["egg", "spam"],
["egg", "bacon", "spam"],
["egg", "bacon", "sausage", "spam"],
["spam", "bacon", "sausage", "spam"],
["spam", "sausage", "spam", "bacon", "spam", "tomato", "spam"],
["spam", "egg", "spam", "spam", "bacon", "spam"],
]
item = "-"
while item in menu != "spam":
continue
if "spam" in menu:
menu.remove("spam")
print(menu)`
I also tried the following:
if item in menu == "spam"
menu.remove("spam")
which results in the same issue.Can anyone help me with this? It's driving me insane.
for items in menu:
for i in items:
if i!='spam':
print(i)
Zanmato's solution is very simple and probably the best for this situation. However, it also changes the original list, which is probably desirable for this particular situation, but if you want to preserve the original list, you can use a list comprehension syntax like this to clean and print the list directly without having to create or overwrite another variable.
menu = [ ["egg", "bacon"],
["egg", "sausage", "bacon"],
["egg", "spam"],
["egg", "bacon", "spam"],
["egg", "bacon", "sausage", "spam"],
["spam", "bacon", "sausage", "spam"],
["spam", "sausage", "spam", "bacon", "spam", "tomato", "spam"],
["spam", "egg", "spam", "spam", "bacon", "spam"],
]
print([[item for item in submenu if item != "spam"] for submenu in menu])

Calculating the semantic descriptor of a nested list

I am trying to calculate the semantic description of a nested list to turn it into a nested dictionary. First I got distinct_words, each word of it will be the keys of my final dictionary.
def build_semantic_descriptors(sentences):
flat_list = [term for group in sentences for term in group]
distinct_words = set(flat_list)
d = {}
for row in sentences:
for words in row:
if words not in d:
d[words] = 1
else:
d[words] += 1
if __name__ == '__main__':
x = [["i", "am", "a", "sick", "man"],
["i", "am", "a", "spiteful", "man"],
["i", "am", "an", "unattractive", "man"],
["i", "believe", "my", "liver", "is", "diseased"],
["however", "i", "know", "nothing", "at", "all", "about", "my",
"disease", "and", "do", "not", "know", "for", "certain", "what", "ails", "me"]]
print(build_semantic_descriptors(x))
EXPECTED OUTPUT: {'i': {'am': 3, 'a': 2, 'sick': 1, 'man': 3, 'spiteful': 1, 'an': 1, 'unattractive': 1, 'believe': 1, 'my': 2, 'liver': 1, 'is': 1, 'diseased': 1, 'however': 1, 'know': 1, 'nothing': 1, 'at': 1, 'all': 1, 'about': 1, 'disease': 1, 'and': 1, 'do': 1, 'not': 1, 'for': 1, 'certain': 1, 'what': 1, 'ails': 1, 'me': 1}, 'am': {'i': 3, 'a': 2, 'sick': 1, 'man': 3, 'spiteful': 1, 'an': 1, 'unattractive': 1}, etc...}
At this moment this is my code. I already got the words I want as the keys, but I don't know how to count the words related to them and put into the final dictionary, I've tried using the counter above, but what it does is calculate the overall value of appearences.
Thanks in advance for any help.
Try this:
from collections import defaultdict
from itertools import product
def build_semantic_descriptors(sentences):
d = defaultdict(lambda: defaultdict(int))
for sentence in sentences:
should_skip_key = True
for (key, word) in product(sentence, sentence):
if key == word and should_skip_key:
should_skip_key = False
continue
d[key][word] += 1
return d
if __name__ == '__main__':
x = [["i", "am", "a", "sick", "man"],
["i", "am", "a", "spiteful", "man"],
["i", "am", "an", "unattractive", "man"],
["i", "believe", "my", "liver", "is", "diseased"],
["however", "i", "know", "nothing", "at", "all", "about", "my",
"disease", "and", "do", "not", "know", "for", "certain", "what", "ails", "me"]]
print(build_semantic_descriptors(x))
You need to loop each sentence twice, in order to get each word for each key. For this you can use itertools.product.
Also note that I use here collections.defaultdict which you should read about, it is a nice utility that sets the dictionary with a default if the key does not exist (allowing to skip the check that you had)

Join dictionaries so that previous dictionary names are now 2nd layer keys?

I am attempting to organize new dictionaries based on the results of a df.groupby('fruits'). I now have dictionaries setup like the following,
print(type(flavors))
<class 'dict'>
print(flavors)
{'apples':['crisp', 'tart'],
'oranges':['citrusy','juicy', 'sour'],
'bananas':['sweet']}
print(colors)
{'apples':['red', 'green'],
'oranges':['orange','orange', 'rotten'],
'bananas':['yellow']}
print(farms)
{'apples':['upstate orchard', 'dreamy estates'],
'oranges':['crop culture','sandy bay', 'heartland'],
'bananas':['horticulture heros']}
How could I join them in a new dictionary like the following?
print(fruits_dict)
{'apples': {'flavors': ['crisp', 'tart'],
'colors': ['red', 'green'],
'farms': ['upstate orchard', 'dreamy estates'] },
'oranges': {'flavors': ['citrusy','juicy', 'sour'],
'colors': ['orange','orange', 'rotten'],
'farms': ['crop culture','sandy bay', 'heartland'] },
'bananas': {'flavors': ['sweet'],
'colors': ['yellow'],
'farms': ['horticulture heros'] } }
dicts = {'flavors' : flavors, 'colors': colors, 'farms' : farms}
result = {key: { k : dicts[k][key] for k in dicts} for key in flavors}
You can use this example with dict comprehension how to get your output:
flavors = {
"apples": ["crisp", "tart"],
"oranges": ["citrusy", "juicy", "sour"],
"bananas": ["sweet"],
}
colors = {
"apples": ["red", "green"],
"oranges": ["orange", "orange", "rotten"],
"bananas": ["yellow"],
}
farms = {
"apples": ["upstate orchard", "dreamy estates"],
"oranges": ["crop culture", "sandy bay", "heartland"],
"bananas": ["horticulture heros"],
}
out = {
k: {
"flavors": flavors.get(k, []),
"colors": colors.get(k, []),
"farms": farms.get(k, []),
}
for k in (flavors.keys() & colors.keys() & farms.keys())
}
from pprint import pprint
pprint(out)
Prints:
{'apples': {'colors': ['red', 'green'],
'farms': ['upstate orchard', 'dreamy estates'],
'flavors': ['crisp', 'tart']},
'bananas': {'colors': ['yellow'],
'farms': ['horticulture heros'],
'flavors': ['sweet']},
'oranges': {'colors': ['orange', 'orange', 'rotten'],
'farms': ['crop culture', 'sandy bay', 'heartland'],
'flavors': ['citrusy', 'juicy', 'sour']}}

How to control the color input of a Sunburst with plotly.graph_objects?

I would like to have control over the colors of each label in the Sunburst diagram below - when using plotly.graph_objects instead of plotly.express.
See example from documentation below:
import plotly.graph_objects as go
fig =go.Figure(go.Sunburst(
labels=[ "Eve", "Cain", "Seth", "Enos", "Noam", "Abel", "Awan", "Enoch", "Azura"],
parents=["", "Eve", "Eve", "Seth", "Seth", "Eve", "Eve", "Awan", "Eve" ],
values=[ 65, 14, 12, 10, 2, 6, 6, 4, 4],
branchvalues="total",
))
fig.update_layout(margin = dict(t=0, l=0, r=0, b=0))
fig.show()
That would allow accessing and control the markers:
import plotly.express as px
greys = px.colors.sequential.Greys
reds = px.colors.sequential.Reds
blues = px.colors.sequential.Blues
greens = px.colors.sequential.Greens
magents = px.colors.sequential.Magenta
fig.data[0].marker.colors = ['', greys[5], reds[5], reds[6], reds[7],
blues[5], greens[5], greens[6], magents[5]]
fig.show()

Python Enchant language descriptions

I'm working with the pyenchant module. I couldn't find in their documentaion and anywhere else, the descriptions for the languages listed in enchant.list_languages(). This function returns a list of tags, I need the human friendly descripction of each language.
import enchant
enchant.list_languages()
['af', 'am', 'ar', 'bg', 'bn', 'br', 'ca', 'cs', 'cy', 'da', 'de', 'de_AT', 'de_CH', 'de_DE', 'el', 'en', 'en_CA', 'en_GB', 'en_US', 'eo', 'es', 'et', 'eu', 'fa', 'fo', 'fr', 'fr_CH', 'fr_FR', 'ga', 'gl', 'gu', 'he', 'hi', 'hr', 'hsb', 'hu', 'hy', 'id', 'is', 'it', 'kk', 'kn', 'ku', 'lt', 'lv', 'ml', 'mr', 'nb', 'nl', 'nn', 'no', 'nr', 'ns', 'or', 'pa', 'pl', 'pt_BR', 'pt_PT', 'ro', 'ru', 'sk', 'sk_SK', 'sl', 'st', 'sv', 'ta', 'te', 'tl', 'tl_PH', 'tn', 'ts', 'uk', 'uz', 'xh', 'zu']
How can I translate all this tags to the human friendly name of these languages ('English', 'Spanish', 'Italian', etc)? Is there a function in pyenchant or another library to accomplish this?
Thanks a lot!!
You can use pycountry:
To get the language name, you can use:
pycountry.languages.get(alpha_2=language)
Where language is one of the pyenchant languages.
EDIT
Here is how you can print the pyenchant language names (and countries):
import pycountry
enchant_codes = [
"af", "am", "ar", "bg", "bn", "br", "ca", "cs", "cy", "da",
"de", "de_AT", "de_CH", "de_DE", "el", "en", "en_CA", "en_GB", "en_US", "eo",
"es", "et", "eu", "fa", "fo", "fr", "fr_CH", "fr_FR", "ga", "gl", "gu",
"he", "hi", "hr", "hsb", "hu", "hy", "id", "is", "it", "kk",
"kn", "ku", "lt", "lv", "ml", "mr", "nb", "nl", "nn", "no", "nr",
"ns", "or", "pa", "pl", "pt_BR", "pt_PT", "ro", "ru", "sk", "sk_SK", "sl",
"st", "sv", "ta", "te", "tl", "tl_PH", "tn", "ts", "uk", "uz", "xh", "zu",
]
for code in enchant_codes:
lang_code, _, country_code = code.partition("_")
if len(lang_code) == 2:
language = pycountry.languages.get(alpha_2=lang_code)
elif len(lang_code) == 3:
language = pycountry.languages.get(alpha_3=lang_code)
else:
language = None
language_name = language.name if language else "(unknown language)"
country = pycountry.countries.get(alpha_2=country_code) if country_code else None
country_name = country.name if country else ""
print(code, "=>", language_name, "/", country_name)

Categories