0

我有一组值 tgat 代表 postcodd 中的平均人数。这些是pcode1 = 239, pcode2 = 245,现在pcode3 = 210pcode4 = 217了我被卡住的地方。我假设平均值是allpcode = 220.

有没有办法在 python 中编写代码,以便我可以将每个单独的 pcode 与总平均值进行比较?我真正想做的是说比较pcode1allpcode如果pcode1高于/低于allpcode显示平均值,pcode1并说pcode1低于allpcode或高于allpcode。然后我想对所有其他 pcode 重复 :)

我想在屏幕上显示所有较低的平均值和所有较高的平均值。

所以像 pcode 3 和 4 的平均值低于所有 pcode 平均值,而 pcode 1 和 2 高于所有 p 码。

是否可以创建这样的代码,因为我不知道如何/从哪里开始?

4

2 回答 2

0

在这种情况下,您经常想要迭代所有一组值,通常最好使用单个list,dict或其他集合变量,而不是一堆单独的变量。例如:

pcodes = {1: 239, 2: 245, 3: 210, 4: 217}

现在您可以编写如下代码:

pcodes = {1: 239, 2: 245, 3: 210, 4: 217}
allpcode = 220

for pcode, value in pcodes.items():
    if value < allpcode:
        print('code {} is lower than allpcode'.format(pcode))
    elif value > allpcode:
        print('code {} is higher than allpcode'.format(pcode))

如果你真的想有单独的变量,你必须做更多的工作,像这样:

pcode1 = 239
pcode2 = 245
pcode3 = 210
pcode4 = 217
allpcode = 220

for i, value in enumerate((pcode1, pcode2, pcode3, pcode4)):
    if value < allpcode:
        print('code {} is lower than allpcode'.format(i + 1))
    elif value > allpcode:
        print('code {} is higher than allpcode'.format(i + 1))
于 2013-05-29T01:06:23.290 回答
0

如果您只想匹配值,则可以使用列表:

>>> pcode1 = 239
>>> pcode2 = 245
>>> pcode3 = 210
>>> pcode4 = 217
>>> lis = [pcode1, pcode2, pcode3, pcode4]
>>> allpcode= 220

>>> for i,x in enumerate(lis):
    if x < allpcode:
        print "pcode{} is less than {}".format(i+1,allpcode)
    elif x > allpcode:    
        print "pcode{} is greater than {}".format(i+1,allpcode)
...         
pcode1 is greater than 220
pcode2 is greater than 220
pcode3 is less than 220
pcode4 is less than 220

更好地使用字典:

由于变量只是对 python 中值的引用,因此您无法访问变量名。如果你有很多pcodes然后为它们中的每一个定义一个变量是解决这个问题的坏方法,那么使用 dict 会更干净。

#create dictionary with keys named pcode1, pcode2,...     
>>> dic = {'pcode1':239, 'pcode2':245, 'pcode3':210, 'pcode4':217}

>>> for k,v in dic.items():
    if v < allpcode:
        print "{} is less than {}".format(k ,'allpcode')
    elif v > allpcode:    
        print "{} is greater than {}".format(k,'allpcode')
...         
pcode3 is less than allpcode
pcode2 is greater than allpcode
pcode1 is greater than allpcode
pcode4 is less than allpcode

尽管字典不维护任何顺序,但您可能必须collections.OrderedDictsorted在这里以特定顺序获取键。

于 2013-05-29T01:07:13.903 回答