Python : What is the purpose of a colon in an if statement?

后端 未结 4 1806
暗喜
暗喜 2021-01-29 17:21

I have this piece of python code below.

def m(list):
    v = list[0]
    for e in list:
        if v < e:
            v = e
        return v

values = [[3, 4,         


        
相关标签:
4条回答
  • 2021-01-29 17:24
    if v < e: v = e
    

    can be read: "If v is less than e, make v the value of e."

    As above you should put a new line to make it read easier:

    if v < e:
        v = e
    
    0 讨论(0)
  • 2021-01-29 17:26

    It's called a colon in english, not a double colon or double comma.

    I urge you to read a basic Python introduction.

    if v < e: v = e
    

    Is the same as:

    if v < e:
        v = e
    
    0 讨论(0)
  • 2021-01-29 17:46
    In [8]: v = 1
    In [9]: e = 2
    In [10]: if v < e: v = e
    In [11]: v
    Out[11]: 2
    In [12]: e
    Out[12]: 2
    

    is same as:

    In [13]: v = 1
    In [14]: e = 2
    In [15]: if v < e:  # if True execute next statement 
       ....:     v = e
       ....:     
    In [16]: v
    Out[16]: 2
    In [17]: e
    Out[17]: 2
    
    0 讨论(0)
  • 2021-01-29 17:48

    Another way to write that code is like this, just for learning purposes:

        def max_nest_list(lst):
            max_numbers = []
            for sub_list in lst:
                max_num = sub_list[0]
                for num in sub_list[1:]:
                    if num > max_num:
                         max_num = num
                max_numbers.append(max_num)
            return max_numbers
    
        values = [[3, 4, 5, 1], [33, 6, 1, 2]]
        for item in max_nest_list(values):
            print(item, end = " ")
    
        #Output
        5 33
    

    Or even more concise:

        def max_nest_list2(lst):
            return [max(i) for i in lst]
    
        values = [[3, 4, 5, 1], [33, 6, 1, 2]]
        for item in max_nest_list(values):
            print(item, end = " ")
    
    0 讨论(0)
提交回复
热议问题