Python: Printing out list without certain item - python

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])

Related

Adding variables to dictionary, same format

I want to make the variables that a user inputs, add to the dictionary. But I want it to be added the way that it currently looks:
bookLogger = [
{'BookName': 'Noise', 'Author': 'Daniel Kahneman', 'Process': 'Reading' },
{'BookName': 'Hunting Party', 'Author': 'Lucy Foley', 'Process': 'Reading'},
{'BookName': 'Superintelligence', 'Author': 'Nick Bostrom', 'Process': 'Not Reading'}
]
The code that I have tried
def AddingBooks():
#User inputs what they want to add tot he library
BName = input("Please enter the book name: ")
BAuthor = input("Enter the books Author: ")
BProcess = input("Are you reading, not reading or haven't started ")
#Want to add this to the bookLogger but in the same format that the
#bookLogger dictionary is in
bookLogger['BookName'] = BName
bookLogger['Author'] = BAuthor
bookLogger['Process'] = BProcess
The error that comes up is list indices must be integers or slices, not str for the bookLogger['BookName'] = BName line.
NOTE:
Not sure how to change it + not sure if that will add it to the bookLogger the way I want it to.
bookLogger is a list that has a dictionary. So You have to push or append the dictionary to the list.
bookLogger = [
{'BookName': 'Noise', 'Author': 'Daniel Kahneman', 'Process': 'Reading' },
{'BookName': 'Hunting Party', 'Author': 'Lucy Foley', 'Process': 'Reading'},
{'BookName': 'Superintelligence', 'Author': 'Nick Bostrom', 'Process': 'Not Reading'}
]
def AddingBooks():
#User inputs what they want to add tot he library
BName = input("Please enter the book name: ")
BAuthor = input("Enter the books Author: ")
BProcess = input("Are you reading, not reading or haven't started ")
#Want to add this to the bookLogger but in the same format that the bookLogger
bookLogger.append({"BookName": BName, "Author": BAuthor, "Process": BProcess})
The error is due to using string as a list index. i.e bookLogger['BookName']. 'BookName' is an index. But you cannot use such string values for the list.
If your logger is
bookLogger = [
{'BookName': 'Noise', 'Author': 'Daniel Kahneman', 'Process': 'Reading' },
{'BookName': 'Hunting Party', 'Author': 'Lucy Foley', 'Process': 'Reading'},
{'BookName': 'Superintelligence', 'Author': 'Nick Bostrom', 'Process': 'Not Reading'}
]
You can write a function this way.
def AddingBooks():
# User inputs what they want to add tot he library
BName = input("Please enter the book name: ")
BAuthor = input("Enter the books Author: ")
BProcess = input("Are you reading, not reading or haven't started ")
# Want to add this to the bookLogger but in the same format that
the
# bookLogger dictionary is in
#first create a dictionary
log = {'BookName': BName,
'Author': BAuthor,
"Process": BProcess}
#bookLogger is a list so you have to append individual log to it
bookLogger.append(log)

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)

How to remove specific item from list?

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

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: Object to list of tuples extraction

I have an object in the following format:
{
'af': {
'bidi': False,
'code': 'af',
'name': 'Afrikaans',
'name_local': 'Afrikaans'
},
'ar': {
'bidi': True,
'code': 'ar',
'name': 'Arabic',
'name_local': 'العربيّة'
},
...
}
This is a list of locales as found in django.conf.locale.LANG_INFO. (see here for full reference: https://github.com/django/django/blob/master/django/conf/locale/init.py).
Now, I am hoping to utilise this list in a model class:
locale = models.CharField(max_length=5, choices=get_locale_choices(), default='en')
Such that I have the following utility function:
from django.conf.locale import LANG_INFO
def get_locale_choices():
return ?
Now, that ? that gets returned, I'd like to be in the following format:
[
('af', 'Afrikaans'),
('ar', 'Arabic'),
...
]
My question is this, how would I turn the LANG_INFO dictionary into the above list of tuples?
It feels like something like this is close:
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
d_items = a_dict.items()
d_items # Here d_items is a view of items
dict_items([('color', 'blue'), ('fruit', 'apple'), ('pet', 'dog')])
But...hmmm, not sure? I want to extract a sub-value from the key item...
Use list comprehension:
from django.conf.locale import LANG_INFO
def get_locale_choices():
return [(k, v['name']) for k, v in LANG_INFO.items() if 'name' in v]
The ... if 'name' in v part is necessary to ensure that the cases that have a 'fallback' but no 'name' (e.g. zh-cn, zh-my, zh-sg, etc.) are ignored.
Result:
[('af', 'Afrikaans'), ('ar', 'Arabic'), ...]
Note: django.conf.locale.LANG_INFO seems to be internal to Django, so your use of it isn't officially sanctioned by Django.

Categories