can someone explain to me how i can addition two value in list of list ?
Here my list of list :
data = [
["Autofollow", 7200, "00:00:00:00", "Name Of File0", "28/07/2021"], # Line 1
["Autofollow", 300 , "00:00:00:00", "Name Of File2", "28/07/2021"], # Line 2
["Autofollow", 3600, "00:00:00:00", "Name Of file3", "28/07/2021"], # Line 3
]
here i generate randomly data :
i = 0
while i <= 2 :
dataRand += random.choices(data)
i += 1
I call the function totalInSecond with list dataRand :
print(totalInSecod(dataRand))
here the function which must add the values of value1 :
def totalInSecod(someRandomData) :
global sumDurationInSecond
print(someRandomData)
for value in someRandomData :
sumDurationInSecond += value[1]
return sumDurationInSecond
but the result does not add all the values of my list of list..
I have this result :
[['Autofollow', 3600, '00:00:00:00', 'Name Of file3', '28/07/2021'], ['Autofollow', 7200, '00:00:00:00', 'Name Of File0', '28/07/2021']]
3600
I would like to have 3600 + 7200 = 10800
I'm sorry if this question has already been asked, but I can't find an answer
as far as i can presume, you want sum of all the elements at index 1
when you look at "sumDurationInSecond += value[1]"
you’ve tried to iterate over an object that is not iterable. if you want to use for loop here, you have to use it using range to grab list's elements.
for example -
def totalInSecod(someRandomData):
sumDurationInSecond = 0
for value in range(len(someRandomData)):
sumDurationInSecond+=(someRandomData[value][1])
print(sumDurationInSecond)
other solution is to append the elements in a list and then return the sum of that list
def totalInSecod(someRandomData):
sumDurationInSecond = []
for value in someRandomData:
sumDurationInSecond.append(value[1])
print(sum(sumDurationInSecond))
You code is absolutely ok. You just have to return the after for loop.
Your Code:
def totalInSecod(someRandomData) :
sumDurationInSecond = 0
for value in someRandomData :
sumDurationInSecond += value[1]
return sumDurationInSecond
data = [
["Autofollow", 7200, "00:00:00:00", "Name Of File0", "28/07/2021"], # Line 1
["Autofollow", 300 , "00:00:00:00", "Name Of File2", "28/07/2021"], # Line 2
["Autofollow", 3600, "00:00:00:00", "Name Of file3", "28/07/2021"], # Line 3
]
print(totalInSecod(data))
OR One Liner
def totalInSecod(someRandomData):
return sum(list(zip(*someRandomData))[1])
data = [
["Autofollow", 7200, "00:00:00:00", "Name Of File0", "28/07/2021"], # Line 1
["Autofollow", 300 , "00:00:00:00", "Name Of File2", "28/07/2021"], # Line 2
["Autofollow", 3600, "00:00:00:00", "Name Of file3", "28/07/2021"], # Line 3
]
print(totalInSecod(data))
Output: 11100
Related
On the multidimensional JSON below i had extracted the "width" and "height" values as i want to append on an empty table/array and use them later for calculations. On the following JSON.
[
{
"frame_id":1,
"filename":"bake/IMG_20210930_090024.jpg",
"objects": [
{"class_id":0, "name":"brick", "relative_coordinates":{"left_x":1279, "top_y": 991, "width": 922, "height":1164},"relevant":true}
]
},
{
"frame_id":2,
"filename":"bake/IMG_20210930_090017.jpg",
"objects": [
{"class_id":1, "name":"limestone", "relative_coordinates":{"left_x":1672, "top_y":1536, "width": 651, "height": 623},"relevant":true}
]
}
]
My code and result:
with open('/home/pan/output/result.json') as json_data:
data = json.load(json_data)
for item in data:
for row in item.get('objects', []):
print(row['class_id'], row['relative_coordinates']['width'],row['relative_coordinates']['height'])
0 922 1164
1 651 623
My main question would be that i would like to show the results only for "class_id":0 for width and height.
Also whats the best way to append those values through the console or an empty array[] and make calculations later?
You can try this:
value_list = []
with open('result.json') as json_data:
data = json.load(json_data)
for item in data:
for row in item.get('objects', []):
if row['class_id'] == 0:
print(row['class_id'], row['relative_coordinates']['width'], row['relative_coordinates']['height'])
value_list.append(row['relative_coordinates']['width'])
value_list.append(row['relative_coordinates']['height'])
print(value_list)
Output:
0 922 1164
[922, 1164]
You get to your data by slogging through the dicts and lists one by one.
width = -1
height = -1
for item in data:
if item['objects'][0]['class_id'] == 0:
width = item['objects'][0]['relative_coordinates']['width']
height = item['objects'][0]['relative_coordinates']['height']
break
Just adding a if condition in your code will give the expected results as below:
data = None
with open('/home/pan/output/result.json') as json_data:
data = json.load(json_data)
co_ordinates = []
for item in data:
for row in item.get('objects', []):
if row['class_id'] == 0:
co_ordinates.append(row['relative_coordinates']['width'])
co_ordinates.append(row['relative_coordinates']['height'])
break
print (co_ordinates)
Output:
[922, 1164]
I was trying to solve the problem But I could not figure it out.
I have product dictionary:
product = {
"shirt" : {
"price" :300 ,
"no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}},
"pents" : {
"price" :200 ,
"no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}}
"tshirt" : {
"price" :150 ,
"no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}}
"shorts" : {
"price" :100 ,
"no_reqired_for_dis" : {"3": ["shirt","pents","tshirt","shorts"],"discount_price" : 250}}
}
What should be best approach to to find the total
discount criteria if anyone who buys a minimum of three products or a multiple of 3 they will get three item for 250?
for example if someone buy total 11 (shirt = 5,pants = 4, tshirt = 1, short = 1) products,then their total should be 250 * 3 + remaining item * lowest price product. Here remaining item should be lowest price of the product(here it should be shorts and tshirt).
I have done this:
total_payment = 0
total_product = {"shirt" : 5,"pents":4,"tshirt":1,"shorts" 1}
total_item = sum(total_product.values())
for key, value in total_product.items():
min_no_required_for_discount = product[key]["no_required_for_dis"].keys()
if total_item < int(min_no_required_for_discount[0]:
total_payment += value * product[key]["price"]
else:
remaining_unit = total_item % 3
total_pair = (total_item - remaining_unit) // 3
total_payment += total_pair * 250
Now i am confuse in remaining_unit. how to calculate price for remaining_unit because remaining_unit must multiply with who has minimum price . in above example remaining_unit will be 2 and it will calculate price of shorts and tshirt
Here is quick template that might help you to start working on this problem:
[Notes: use set() to get the items difference quickly, and use print() statement to confirm each step is expected] Again, this is NOT a complete solution - but just offers a good template for you to start quickly.
from pprint import pprint
lowest_price_items = ['tshirt', 'shorts']
discount_price_items = ['shirt', 'pants']
discount_Set = set(discount_price_items)
cart = ['shirt', 'shirt', 'shirt', 'shirt', 'shirt', 'pants', 'pants', 'pants', 'pants', 'tshirt', 'shorts']
cart_Set = set(cart)
low_price_goods = cart_Set - discount_Set
pprint(product)
print(f' products: {product.keys()} ') # first level of prod. dict.
print(product['shirt'].keys()) # 'price' and 'no_requied_for_dis'
# products key1 key2
print(product['shirt']['no_reqired_for_dis']['discount_price']) # 250
tshirt_price = product['tshirt']['price']
print(tshirt_price)
"""
total should be 250 * 3 + remaining item * lowest_price_products (tshirts, shorts) only
"""
total_items = len(cart)
print(total_items)
# modify this to calculate the final price.
if total_items > 3:
final_price = 250 * total_items %3 + "remaining item * lowest_price_products" # select the lowest price items
I have a dict as below, if the same value is found more tahn once then the dict key must be created with incremental numbering.
TT = {
"TYPE_1" : ['ERROR'],
"TYPE_2": ['FATAL'],
"TYPE_3" : ["TIME_OUT"],
"TYPE_4" : ['SYNTAX'],
"TYPE_5" : ['COMPILE'],
}
m1 = "ERROR the input is not proper"
m2 = "This should have not occured FATAL"
m3 = "Sorry TIME_OUT"
m4 = "SYNTAX not proper"
m5 = "u r late its TIME_OUT"
The value "TIME_OUT" occur twice in the search.
count = 0
for key in TT.keys():
print(key)
Key_1 = key
while key_1 in TT:
count = count+1
key_1 = key + "_{}".format(count)
The above code gives error Key_1 not defined.
Expected OUTPUT:
if the same value is occuring more than once then the dict key should be created with incremental numbering "TYPE_3_1" : ["TIME_OUT"],
TT = {
"TYPE_1" : ['ERROR'],
"TYPE_2": ['FATAL'],
"TYPE_3" : ["TIME_OUT"],
"TYPE_3_1" : ["TIME_OUT"],
"TYPE_4" : ['SYNTAX'],
"TYPE_5" : ['COMPILE'],
}
Please suggest on this.
There can be a much efficient way of solving this if you can rethink about some of the data structure but if that is not an option you may be able to try this.
inputs = ["ERROR the input is not proper",
"This should have not occured FATAL",
"Sorry TIME_OUT",
"SYNTAX not proper",
"u r late its TIME_OUT"]
basic_types = {
"TYPE_1" : ['ERROR'],
"TYPE_2": ['FATAL'],
"TYPE_3" : ["TIME_OUT"],
"TYPE_4" : ['SYNTAX'],
"TYPE_5" : ['COMPILE'],
}
type_counts = {}
results = {}
for sentence in inputs:
for basic_type in basic_types:
if basic_types.get(basic_type)[0] in sentence:
type_counts[basic_type] = type_counts.get(basic_type, 0) + 1
if type_counts[basic_type] == 1:
results[basic_type] = [basic_types.get(basic_type)[0]]
else:
results[basic_type+"_{}".format(type_counts[basic_type] - 1)] = [basic_types.get(basic_type)[0]]
print(results)
I get the error onthis line of code -
result_dict['strat'][k]['name'] = current_comps[0].strip()
The error is : Keyerror: 'strat'
I have an input line
PERSON1 ## CAR1 # ENTRY : 0 | EXIT : 0 ## CAR2 # M1 : YES : 10/01/17 02:00 | M2 : NO : 10/02/16 03:00 | M3 : NO : 05/07/17 11:00 | M4 : YES : 01/01/16 03:00 ## TRUCK # M3 : NO : 03/01/17 03:45 | M23 : NO : 01/01/14 07:00 | M27 : YES : 02/006/18 23:00
I 'm looking to parse this input to generate the output detailed below. As part of this, I'm trying to build a dictionary inserting both keys & values dynamically. I'm having a lot of problems doing this.
Could I please request help on this?
Here is what I've tried so far -
# File read
f = open('input_data', 'r')
file_cont = f.read().splitlines()
f.close()
#json template
# Initialize dictionary
result_arr = []
result_dict = {}
k = 0
for item in file_cont:
strat = item.split('##')
result_dict['Person'] = strat[0].strip()
j = 1
while j < len(strat):
# Split various components of the main line
current_comps = strat[j].split('#')
# Name of strat being parsed
result_dict['strat'][k]['name'] = current_comps[0].strip()
# tfs across the various time frames
tfs = current_comps[1].split('|')
# First travel mode
if current_comps[0].strip() == 'CAR1':
temp_low_arr = tfs[0].split(':')
temp_high_arr = tfs[1].split(':')
result_dict['strat'][k]['Entry'] = temp_low_arr[1].strip()
result_dict['strat'][k]['Exit'] = temp_high_arr[1].strip()
# Second travel mode
elif current_comps[0].strip() == 'CAR2':
z = 0
while z < len(tfs):
# Split components of the sign
sign_comp_car_2 = tfs[z].split(':')
result_dict['strat'][k]['tf'][z]['path'] = sign_comp_ma_cross[0].strip()
result_dict['strat'][k]['tf'][z]['sign'] = sign_comp_ma_cross[1].strip()
result_dict['strat'][k]['tf'][z]['sign_time'] = sign_comp_ma_cross[2].strip()
z += 1
# Third travel mode
elif current_comps[0].strip() == 'CAR3':
b = 0
while b < len(tfs):
# Split components of the sign
sign_car_3 = tfs[z].split(':')
result_dict['strat'][k]['tf'][b]['path'] = sign_all_term[0].strip()
result_dict['strat'][k]['tf'][b]['sign'] = sign_all_term[1].strip()
result_dict['strat'][k]['tf'][b]['sign_time'] = sign_all_term[2].strip()
b += 1
j += 1
k += 1
Expected output
[{
"Person":"",
"Transport":[
{
"Name":"CAR1",
"Entry":"0",
"Exit":"0"
},
{
"name":"CAR2:",
"tf":[
{
"path":"M1",
"sign":"YES",
"sign_time":"10/01/17 02:00"
},
{
"path":"M2",
"sign":"NO",
"sign_time":"10/02/16 03:00"
},
{
"path":"M3",
"sign":"NO",
"sign_time":"05/07/17 11:00"
},
{
"path":"M4",
"sign":"YES",
"sign_time":"01/01/16 03:00"
}
]
},
{
"name":"CAR3",
"tf":[
{
"path":"M3",
"sign":"NO",
"sign_time":"03/01/17 03:45"
},
{
"path":"M23",
"sign":"NO",
"sign_time":"01/01/14 07:00"
},
{
"path":"M27",
"sign":"Yes",
"sign_time":"02/006/18 23:00"
}
]
}
]
}]
The issue is when you try to assign the ['name'] field in result_dict['strat'][k] when result_dict['strat'][k] hasn't been initialized yet. Before you run your for-loop, the dictionary has no key called strat.
Now you could have done something like result_dict['strat'] = dict() (assigning an object to that key in the dict), but when you further subscript it using result_dict['strat'][k], it will try to resolve that first, by accessing result_dict['strat'], expecting either a subscriptable collection or a dictionary in return. However, since that key doesn't exist yet, it throws you the error.
What you could do instead is initialize a default dictionary:
from collections import defaultdict
...
resultdict = defaultdict(dict)
...
Otherwise, in your existing code, you could initialize a dict within result_dict before entering the loop.
I am new to python basically, I want this dictionary:
ages = {
"toddler" : range(0,2),
"kid" : range(3,12),
"teen" : range(13,19),
"young adult" : range(20,25),
"adult" : range(26,39),
"middle-aged" : range(40,60),
"old" : range(61,99)
}
I have a target_age variable which holds the random value in any of the keys in the above mentioned dictionary:
target_age = random.choice(list(ages))
my api is going to return an "age" which I want to compare if its in the range of the randomized "target_age" variable
How should I code my "if and else statement" if I want for example the returned_age is 25 and the target_age is "young adult" then it should satisfy the condition otherwise it should return false
returned_age in ages[target_age], as mentioned by #khelwood above, sounds like it would accomplish what you want:
ages = {
'toddler': range(0,3),
'kid': range(3,13),
'teen': range(13,20),
'young adult': range(20,26),
'adult': range(26,40),
'middle-aged': range(40,61),
'old': range(61,99)
}
# generate a random target_age
target_age = np.random.choice(list(ages))
# suppose the returned_age from the API is 25
returned_age = 25
print('target_age = ' + str(target_age))
print('returned_age = ' + str(returned_age))
print('returned_age in target_age? ' + str(returned_age in ages[target_age]))
Here is the output from one particular run:
target_age = old
returned_age = 25
returned_age in target_age? False