Dinner = ['Meat', 'Veg', 'Milk', 'Grains']
DinneronMonday = ['Meat', 'Veg', 'Milk', 'Grains']
DinneronTuesday = ['Meat', 'Veg', 'Milk', 'Grains']
DinneronWednesday = ['Meat', 'Veg', 'Milk', 'Grains']
DinneronThursday = ['Meat', 'Veg', 'Milk', 'Grains']
DinneronFriday = ['Meat', 'Veg', 'Milk', 'Grains']
DinneronSaturday = ['Meat', 'Veg', 'Milk', 'Grains']
DinneronSunday = ['Meat', 'Veg', 'Milk', 'Grains']
I need help with overwrting elements in list, i know how to overwrite them however i don't know how to overwrite them using user input for example for dinner on monday i want to change all of the categories
You can use the python input method to set the options for each day. For example:
monday0 = input("Enter option 1 for Monday: ")
DinneronMonday[0] = monday0
// Add input for each
You could also store the input in some other collection structure and set the days options accordingly. That's an assignment for the user ;)
Edit:
You could read the values into a list assuming your input is comma separated
// Input should look like - Steak,Chicken,Fish,Tacos
options = input("Enter options for Monday: ")
DinneronMonday = list(options.split(','))
// Do the same for each day
I'm not quite sure what you want, but I read your question as though you want to get input from user that you set as every element in one of your menu lists. If so, something like this might help:
newItem = input("New menu item: ")
DinneronMonday = [newItem for oldItem in DinneronMonday]
Related
im trying to add variables to a list that i created. Got a result from a session.execute.
i´ve done this:
def machine_id(session, machine_serial):
stmt_raw = '''
SELECT
id
FROM
machine
WHERE
machine.serial = :machine_serial_arg
'''
utc_now = datetime.datetime.utcnow()
utc_now_iso = pytz.utc.localize(utc_now).isoformat()
utc_start = datetime.datetime.utcnow() - datetime.timedelta(days = 30)
utc_start_iso = pytz.utc.localize(utc_start).isoformat()
stmt_args = {
'machine_serial_arg': machine_serial,
}
stmt = text(stmt_raw).columns(
#ts_insert = ISODateTime
)
result = session.execute(stmt, stmt_args)
ts = utc_now_iso
ts_start = utc_start_iso
ID = []
for row in result:
ID.append({
'id': row[0],
'ts': ts,
'ts_start': ts_start,
})
return ID
In trying to get the result over api like this:
def form_response(response, session):
result_machine_id = machine_id(session, machine_serial)
if not result_machine_id:
response['Error'] = 'Seriennummer nicht vorhanden/gefunden'
return
response['id_timerange'] = result_machine_id
Output looks fine.
{
"id_timerange": [
{
"id": 1,
"ts": "2020-08-13T08:32:25.835055+00:00",
"ts_start": "2020-07-14T08:32:25.835089+00:00"
}
]
}
Now i only want the id from it as a parameter for another function. Problem is i think its not a list. I cant select the first element. result_machine_id[0] result is like the posted Output. I think in my first function i only add ts & ts_start to the first row? Is it possible to add emtpy rows and then add 'ts':ts as value?
Help would be nice
If I have understood your question correctly ...
Your output looks like dict. so access its id_timerange key which gives you a list. Access the first element which gives you another dict. On this dict you have an id key:
result_machine_id["id_timerange"][0]["id"]
I am new in python, I created telegram bot with python 3.
to show product from db I write code like that ,
cart: Dict[List[db.Product, int]] = {}
for product in products:
if product.price is None:
continue
message = product.send_as_message(self.chat.id)
cart[message['result']['message_id']] = [product, 0]
inline_keyboard = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(strings.menu_add_to_cart,
callback_data="cart_add")]])
if product.image is None:
self.bot.edit_message_text(chat_id=self.chat.id,
message_id=message['result']['message_id'],
text=product.text(),
reply_markup=inline_keyboard)
else:
self.bot.edit_message_caption(chat_id=self.chat.id,
message_id=message['result']['message_id'],
caption=product.text(),
reply_markup=inline_keyboard)
problem is when I want remove this product , I can't remove image of product , I used cart.clear() but it doesnt work?
I found solution how to remove item from dict "del my_dict['key'] ". I my case I deleted message which show my product
self.bot.delete_message(chat_id=self.chat.id,
message_id=temp_msg,
caption=' ',
reply_markup=None)
I have some names and scores as follows
input = {
'Maths': dict(Mohsen=19, Sadegh=18, Hafez=15),
'Physics': dict(Sadegh=16, Hafez=17, Mohsen=17),
'Chemistry': dict(Hafez=13),
'Literature': dict(Sadegh=14),
'Biology': dict(Mohsen=16, Sadegh=10),
}
if a person don't have any lesson its score consider zero also get avrege of scores's person and sort final list by averge and i want to get an output like this.
answer = [
dict(Name='Sadegh', Literature=14, Chemistry=0, Maths=18, Physics=16, Biology=10, Average=11.6),
dict(Name='Mohsen', Maths=19, Physics=17, Chemistry=0, Biology=16, Literature=0, Average=10.4),
dict(Name='Hafez', Chemistry=13, Biology=0, Physics=17, Literature=0, Maths=15, Average=9),
]
how to do it?
Essentially, you have a dictionary, where the information is arranged based on subjects, where for each subject, you have student marks. You want to collection all information related to each student in separate dictionaries.
One of the approaches which can try, is as below:
Try converting the data which you have into student specific data and then you can calculate the Average of the Marks of all subjects for that student. There is a sample code below.
Please do note that, this is just a sample and you should be trying
out a solution by yourself. There are many alternate ways of doing it and you should explore them by yourself.
The below code works with Python 2.7
from __future__ import division
def convert_subject_data_to_student_data(subject_dict):
student_dict = {}
for k, v in subject_dict.items():
for k1, v1 in v.items():
if k1 not in student_dict:
student_dict[k1] = {k:v1}
else:
student_dict[k1][k] = v1
student_list = []
for k,v in student_dict.items():
st_dict = {}
st_dict['Name'] = k
st_dict['Average'] = sum(v.itervalues()) / len(v.keys())
st_dict.update(v)
student_list.append(st_dict)
print student_list
if __name__ == "__main__":
subject_dict = {
'Maths': dict(Mohsen=19, Sadegh=18, Hafez=15),
'Physics': dict(Sadegh=16, Hafez=17, Mohsen=17),
'Chemistry': dict(Hafez=13),
'Literature': dict(Sadegh=14),
'Biology': dict(Mohsen=16, Sadegh=10),
}
convert_subject_data_to_student_data(subject_dict)
sample_input = {
'Maths': dict(Mohsen=19, Sadegh=18, Hafez=15),
'Physics': dict(Sadegh=16, Hafez=17, Mohsen=17),
'Chemistry': dict(Hafez=13),
'Literature': dict(Sadegh=14),
'Biology': dict(Mohsen=16, Sadegh=10),
}
def foo(lessons):
result = {}
for lesson in lessons:
for user in lessons[lesson]:#dictionary
if result.get(user):
#print(result.get(user))
result.get(user).setdefault(lesson, lessons[lesson].get(user,0))
else:
result.setdefault(user, dict(name=user))
result.get(user).setdefault(lesson,lessons[lesson].get(user,0))
#return list(result.values())
return result.values()
#if name == '__main__':
print(foo(sample_input))
I have a use case where I have multiple line plots (with legends), and I need to update the line plots based on a column condition. Below is an example of two data set, based on the country, the column data source changes. But the issue I am facing is, the number of columns is not fixed for the data source, and even the types can vary. So, when I update the data source based on a callback when there is a new country selected, I get this error:
Error: attempted to retrieve property array for nonexistent field 'pay_conv_7d.content'.
I am guessing because in the new data source, the pay_conv_7d.content column doesn't exist, but in my plot those lines were already there. I have been trying to fix this issue by various means (making common columns for all country selection - adding the missing column in the data source in callback, but still get issues.
Is there any clean way to have multiple line plots updating using callback, and not do a lot of hackish way? Any insights or help would be really appreciated. Thanks much in advance! :)
def setup_multiline_plots(x_axis, y_axis, title_text, data_source, plot):
num_categories = len(data_source.data['categories'])
legends_list = list(data_source.data['categories'])
colors_list = Spectral11[0:num_categories]
# xs = [data_source.data['%s.'%x_axis].values] * num_categories
# ys = [data_source.data[('%s.%s')%(y_axis,column)] for column in data_source.data['categories']]
# data_source.data['x_series'] = xs
# data_source.data['y_series'] = ys
# plot.multi_line('x_series', 'y_series', line_color=colors_list,legend='categories', line_width=3, source=data_source)
plot_list = []
for (colr, leg, column) in zip(colors_list, legends_list, data_source.data['categories']):
xs, ys = '%s.'%x_axis, ('%s.%s')%(y_axis,column)
plot.line(xs,ys, source=data_source, color=colr, legend=leg, line_width=3, name=ys)
plot_list.append(ys)
data_source.data['plot_names'] = data_source.data.get('plot_names',[]) + plot_list
plot.title.text = title_text
def update_plot(country, timeseries_df, timeseries_source,
aggregate_df, aggregate_source, category,
plot_pay_7d, plot_r_pay_90d):
aggregate_metrics = aggregate_df.loc[aggregate_df.country == country]
aggregate_metrics = aggregate_metrics.nlargest(10, 'cost')
category_types = list(aggregate_metrics[category].unique())
timeseries_df = timeseries_df[timeseries_df[category].isin(category_types)]
timeseries_multi_line_metrics = get_multiline_column_datasource(timeseries_df, category, country)
# len_series = len(timeseries_multi_line_metrics.data['time.'])
# previous_legends = timeseries_source.data['plot_names']
# current_legends = timeseries_multi_line_metrics.data.keys()
# common_legends = list(set(previous_legends) & set(current_legends))
# additional_legends_list = list(set(previous_legends) - set(current_legends))
# for legend in additional_legends_list:
# zeros = pd.Series(np.array([0] * len_series), name=legend)
# timeseries_multi_line_metrics.add(zeros, legend)
# timeseries_multi_line_metrics.data['plot_names'] = previous_legends
timeseries_source.data = timeseries_multi_line_metrics.data
aggregate_source.data = aggregate_source.from_df(aggregate_metrics)
def get_multiline_column_datasource(df, category, country):
df_country = df[df.country == country]
df_pivoted = pd.DataFrame(df_country.pivot_table(index='time', columns=category, aggfunc=np.sum).reset_index())
df_pivoted.columns = df_pivoted.columns.to_series().str.join('.')
categories = list(set([column.split('.')[1] for column in list(df_pivoted.columns)]))[1:]
data_source = ColumnDataSource(df_pivoted)
data_source.data['categories'] = categories
Recently I had to update data on a Multiline glyph. Check my question if you want to take a look at my algorithm.
I think you can update a ColumnDataSource in three ways at least:
You can create a dataframe to instantiate a new CDS
cds = ColumnDataSource(df_pivoted)
data_source.data = cds.data
You can create a dictionary and assign it to the data attribute directly
d = {
'xs0': [[7.0, 986.0], [17.0, 6.0], [7.0, 67.0]],
'ys0': [[79.0, 69.0], [179.0, 169.0], [729.0, 69.0]],
'xs1': [[17.0, 166.0], [17.0, 116.0], [17.0, 126.0]],
'ys1': [[179.0, 169.0], [179.0, 1169.0], [1729.0, 169.0]],
'xs2': [[27.0, 276.0], [27.0, 216.0], [27.0, 226.0]],
'ys2': [[279.0, 269.0], [279.0, 2619.0], [2579.0, 2569.0]]
}
data_source.data = d
Here if you need different sizes of columns or empty columns you can fill the gaps with NaN values in order to keep column sizes. And I think this is the solution to your question:
import numpy as np
d = {
'xs0': [[7.0, 986.0], [17.0, 6.0], [7.0, 67.0]],
'ys0': [[79.0, 69.0], [179.0, 169.0], [729.0, 69.0]],
'xs1': [[17.0, 166.0], [np.nan], [np.nan]],
'ys1': [[179.0, 169.0], [np.nan], [np.nan]],
'xs2': [[np.nan], [np.nan], [np.nan]],
'ys2': [[np.nan], [np.nan], [np.nan]]
}
data_source.data = d
Or if you only need to modify a few values then you can use the method patch. Check the documentation here.
The following example shows how to patch entire column elements. In this case,
source = ColumnDataSource(data=dict(foo=[10, 20, 30], bar=[100, 200, 300]))
patches = {
'foo' : [ (slice(2), [11, 12]) ],
'bar' : [ (0, 101), (2, 301) ],
}
source.patch(patches)
After this operation, the value of the source.data will be:
dict(foo=[11, 22, 30], bar=[101, 200, 301])
NOTE: It is important to make the update in one go to avoid performance issues
`list1 = ["Arizona","Atlanta","Baltimore","Buffalo","Carolina","Chicago",
"Cincinnati","Cleveland","Dallas","Denver","Detroit","Green Bay","Houston",
"Indianapolis","Jacksonville","Kansas City","L.A. Chargers","L.A. Rams",
"Miami","Minnesota","New England","New Orleans","NY Giants","NY Jets",
"Oakland","Philadelphia","Pittsburgh","San Francisco","Seattle",
"Tampa Bay","Tennessee","Washington"]
a = "New Orleans at Oakland"
k = a.find("at")
print (k)
for n in range(0,31):
# b = list1[n]
# print(b[0:k-1]+" "+a[0:k-1])
idx = a.find(list1[n], 0, k-1)
if idx > 0:
print(n)
break
print ("awa team at index" + str(n+1))
for n in range(0,31):
idx = a.find(list1[n], k+2, len(a))
if idx > 0:
print(n)
break
print ("hom team at index" + str(n+1))`
I just started python 2 days ago and I cannot get this to work completely. The program finds the team in the second for loop correctly, but doesn't find the team in the first for loop. I put in the statements that are commented out to see if the strings were somehow truncated, but they are correct. Can anyone tell me what is wrong here?
There's no need to brute force the search. Python has methods that accomplish what you need.
list1 = ["Arizona", "Atlanta", "Baltimore", "Buffalo", "Carolina", "Chicago",
"Cincinnati", "Cleveland", "Dallas", "Denver", "Detroit", "Green Bay", "Houston",
"Indianapolis", "Jacksonville", "Kansas City", "L.A. Chargers", "L.A. Rams",
"Miami", "Minnesota", "New England", "New Orleans", "NY Giants", "NY Jets",
"Oakland", "Philadelphia", "Pittsburgh", "San Francisco", "Seattle",
"Tampa Bay", "Tennessee", "Washington"]
a = "New Orleans at Oakland"
# Create a list of the teams involved in the game
teams = a.split(" at ")
# Iterate through the teams involved in the game
for team in teams:
# The index() method returns the lowest index in list that obj appears
index = list1.index(team)
# If the the team was found then index is valid
if index:
print(index)
print(list1[index])
if you just want to have the index, you can use the .index() you do not have to "loop"
Example code:
list1 = ["Arizona","Atlanta","Baltimore","Buffalo","Carolina","Chicago",
"Cincinnati","Cleveland","Dallas","Denver","Detroit","Green Bay","Houston",
"Indianapolis","Jacksonville","Kansas City","L.A. Chargers","L.A. Rams",
"Miami","Minnesota","New England","New Orleans","NY Giants","NY Jets",
"Oakland","Philadelphia","Pittsburgh","San Francisco","Seattle",
"Tampa Bay","Tennessee","Washington"]
a = "New Orleans at Oakland"
a = a.split(' at ')
idx_home_team = list1.index(a[0])
idx_away_team = list1.index(a[1])
print(idx_home_team, idx_away_team)