Python: 如何让这段代码看起来更漂亮、优雅、Pythonic、简单、更短?
Python: How to make this code look more beautiful ,elegant ,Pythonic ,simple ,shorter?
这是我的代码,对于这么简单的东西来说它非常庞大,我应该如何改进它?
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)))
您不需要创建 charList
;只需使用 dict.values()
:
from statistics import mean
char_stats = {'health': 50 ,'damage': 10.1}
print(int(mean(char_stats.values())))
您可以创建一个 class 对象并重复使用此代码,
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
这是我的代码,对于这么简单的东西来说它非常庞大,我应该如何改进它?
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)))
您不需要创建 charList
;只需使用 dict.values()
:
from statistics import mean
char_stats = {'health': 50 ,'damage': 10.1}
print(int(mean(char_stats.values())))
您可以创建一个 class 对象并重复使用此代码,
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