简体   繁体   English

Python - 如何用字符串计算二维列表中的整数?

[英]Python - How to calculate integers in 2D list with strings?

I should create a program to calculate max, min and avg temperature in the list.我应该创建一个程序来计算列表中的最大、最小和平均温度。 List contain name of month, max and min temperature in this month:列表包含月份名称,当月最高和最低温度:

  months =   [ ["January", 6,3],
               ["February", 7,3],
               ["March", 10,4],
               ["April", 13,6],
               ["May", 17,9],
               ["June", 20,12],
               ["July", 22,14],
               ["August", 21,14],
               ["September",19,12],
               ["October", 14,9],
               ["November", 10,6],
               ["December", 7,3] ]

I have played a bit with code to find out how can I calculate max temperature by using for loop, but it's not working as planned:我玩了一些代码来找出如何通过使用 for 循环来计算最高温度,但它没有按计划工作:

for m in months:
        for temp in m:
            if temp > temp1:
                temp = maxTemp
                print(temp)
                

I'm receiving TypeError:'>' not supported between instances of 'str' and 'int'我收到TypeError:'>' not supported between instances of 'str' and 'int'

What is a correct way to work with list that contain strings in my case?在我的情况下,使用包含字符串的列表的正确方法是什么?

You're running the for loop through all elements in the list, to look only at the temperatures, you could use您正在通过列表中的所有元素运行 for 循环,仅查看温度,您可以使用

for m in months:
    for temp in m[1:]:

which looks only at the integer elements in the list which are the 2nd and 3rd element, and ignores the 1st element which is a string and cannot be compared with integers (and that's the source of your error as well).它只查看列表中的第 2 个和第 3 个元素的整数元素,并忽略第一个元素,它是一个字符串,不能与整数进行比较(这也是错误的来源)。

Your first for loop will yield not the month name, but the list containing ['Mont name', temp1, temp2] .您的第一个for循环不会产生月份名称,而是包含['Mont name', temp1, temp2]

So, your code should be as follows:因此,您的代码应如下所示:

for m in months:
    m_name = m[0]
    temp_vals = m[1:]  # if you have more than two temperature values
    
    temp_min = min(temp_vals)
    temp_avr = sum(temp_vals)/len(temp_vals)
    temp_max = max(temp_vals)

    print(f'{m_name}: T_min = {temp_min}; T_avr = {temp_avr}; T_max = {temp_max};')

Which gives:这使:

January: T_min = 3; T_avr = 4.5; T_max = 6;
February: T_min = 3; T_avr = 5.0; T_max = 7;
March: T_min = 4; T_avr = 7.0; T_max = 10;
April: T_min = 6; T_avr = 9.5; T_max = 13;
May: T_min = 9; T_avr = 13.0; T_max = 17;
June: T_min = 12; T_avr = 16.0; T_max = 20;
July: T_min = 14; T_avr = 18.0; T_max = 22;
August: T_min = 14; T_avr = 17.5; T_max = 21;
September: T_min = 12; T_avr = 15.5; T_max = 19;
October: T_min = 9; T_avr = 11.5; T_max = 14;
November: T_min = 6; T_avr = 8.0; T_max = 10;
December: T_min = 3; T_avr = 5.0; T_max = 7;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM