Home > OS >  Python: How to make this code look more beautiful ,elegant ,Pythonic ,simple ,shorter?
Python: How to make this code look more beautiful ,elegant ,Pythonic ,simple ,shorter?

Time:06-03

This is my code ,it is extremely big for something this simple ,how should i make it better?

import numpy

charStats = {'health': 50 ,'damage': 10.1}
charList = []
numbyO = -1
for x in charStats:
    numbyO  = 1
    charList.append(charStats[x])
print(int(numpy.mean(charList)))

CodePudding user response:

You don't need to create charList; just use dict.values():

from statistics import mean

char_stats = {'health': 50 ,'damage': 10.1}
print(int(mean(char_stats.values())))

CodePudding user response:

You can creat a class object and reuse this code,,,

import numpy                 

class GetMean:
"""make a class object that takes a dict. argument"""
def __init__(self, dict_argument):
    #creat dict. attribute 
    self.dict_argument = dict_argument
    
    #creat list attribute
    self.char_list = []
    
    #creat numby_0 attribute
    self.numby_0 = -1
    
def return_mean(self):
    #method that returns mean
    for x in self.dict_argument:
        self.numby_0  =1
        self.char_list.append(self.dict_argument[x])
    mean = (int(numpy.mean(self.char_list)))
    return mean


charStats = {'health': 50 ,'damage': 10.1}

get_mean = GetMean(charStats) 
#instanting GetMean object

mean = get_mean.return_mean() 
#using return mean method

 print(mean) #showing result


    
  • Related