2013-04-30 127 views
0

我想找到一组数据中的最高温度,并将输出结果打印为“最热的温度是x的y”,其中x和y分别是温度和城市。我有这样的代码:与python输出混淆

data = [['Sheffield', '41.2', '35.5', '41.1'], 
     ['Lancaster', '31.3', '40.2', '37.9'], 
     ['Southampton', '34.8', '33.9', '32',], 
     ['Manchester', '41.9', '41.5', '44.2'], 
     ['Bristol', '42.1', '37.1', '42.2']] 

hot = [] 
for row in data: 
    for item in row: 
     if item == max(row[1:]): 
      hot.append(item) 

    if max(hot) in row: 
     print "The hottest temperature was {0} in {1}.".format(max(hot),row[0]) 

。制得的输出:

The hottest temperature was 41.2 in Sheffield. 
The hottest temperature was 44.2 in Manchester. 

现在我很困惑与输出。我想只打印一行应该是“曼切斯特最热的温度是44.2”的输出。因为44.2是数据中的最高温度。为什么“谢菲尔德最热的温度是41.2”。也打印?我在哪里弄错了?

回答

1

您检查的hot最大值是row的每一行,而不是所有行已被处理后检查一次。

试试这个:

hot = [] 
for row in data: 
    for item in row: 
     if item == max(row[1:]): 
      hot.append(item) 

    if max(hot) in row: 
     max_row = row 

print "The hottest temperature was {0} in {1}.".format(max(hot),max_row[0]) 

顺便说一句,你是存储所有的温度为字符串,而不是浮动。如果温度分布更广(例如'5' > '35.3'为真),则可能会得到奇怪的结果。

+0

谢谢您的解决方案。现在我知道我错了。 – 2013-04-30 13:34:21

1

您在迭代时正在建立列表,并且max正在对列表进行操作目前为止。当你到达谢菲尔德时,这是迄今为止最热门的,所以它打印。但它不知道曼彻斯特更热,因为它还没有看到它。

解决这个问题的最快方法是做两个循环:一个建立列表,然后第二个找到最热门的。

(而且,44.2曼彻斯特?在你的梦想。)

0

首先,我想说这是不是有效的方式来做你想做的。但如果你想知道为什么你会得到这个结果,我会为你解释;

  1. 您正在为每个数据列表元素创建热列表,并在热列表中查找最大值。在第一个循环中它是41.2,它确实在第一行中。所以,它通常打印它。
  2. 直到循环用于第三个列表元素的数据,没有最大值超过41.2,并且没有打印。
  3. 当循环用于数据中的第三个列表元素时,最大值为44.2并且它被打印,并且在现在之后没有最大值,并且将不会打印。
1
data = [['Sheffield', '41.2', '35.5', '41.1'], 
    ['Lancaster', '31.3', '40.2', '37.9'], 
    ['Southampton', '34.8', '33.9', '32',], 
    ['Manchester', '41.9', '41.5', '44.2'], 
    ['Bristol', '42.1', '37.1', '42.2']] 

hot = [] 
for row in data: 
    for item in row: 
     if item == max(row[1:]): 
      hot.append(item) 

for row in data: 
    if max(hot) in row: 
     print "The hottest temperature was {0} in {1}.".format(max(hot),row[0]) 

试试上面的一个,你预计这应该工作...

+0

堆栈溢出答案中的代码应该被解释,而不仅仅是被粘贴,以使提出问题的用户理解你的答案。 – whatyouhide 2013-04-30 13:39:29

+0

这也适用。谢谢! – 2013-04-30 13:42:47

+0

@whatyouhide:感谢您的建议,我从现在开始发布最近的答案,我严格按照您的建议。 – PBD 2013-04-30 13:45:48

0

两行,颇有“Python的”做它的方式:

hot = sorted([(max(x[1:]), x[0]) for x in data], key=lambda x: x[0])[-1] 
print "The hottest temperature was {0} in {1}.".format(*hot)