zoukankan      html  css  js  c++  java
  • 大爽Python入门教程 3-6 答案

    大爽Python入门公开课教案
    点击查看教程总目录

    1 求平方和

    使用循环,计算列表所有项的平方和,并输出这个和。
    列表示例

    lst = [8, 5, 7, 12, 19, 21, 10, 3, 2, 11]
    

    答案代码示例

    lst = [8, 5, 7, 12, 19, 21, 10, 3, 2, 11]
    
    s = 0
    for item in lst:
        s += item * item
    
    print(s)
    

    输出

    1318
    

    2 寻找最小值

    使用循环和判断,寻找出列表的最小值,并输出该最小值及其索引。
    列表示例

    lst = [8, 5, 7, 12, 19, 21, 10, 3, 2, 11]
    

    答案代码示例

    lst = [8, 5, 7, 12, 19, 21, 10, 3, 2, 11]
    
    min_index = 0
    min_value = lst[min_index]
    for i in range(1, len(lst)):
        if lst[i] < min_value:
            min_index = i
            min_value = lst[i]
    
    print("Min Value: %s" % min_value )
    print("Min Value's index: %s" % min_index )
    

    输出

    Min Value: 2
    Min Value's index: 8
    

    3 寻找最长字符串

    使用循环和判断,寻找出列表的最长字符串,并输出该字符串及其索引。
    列表示例

    lst = ["range", "str", "continue", 12, True, "python", 3.14, "else"]
    

    补充说明:列表中有些项并不是字符串(并不是我写错了),
    大家想想要怎么处理这些,没思路的话,建议仔细回顾一下本章所学内容。

    答案代码示例

    lst = ["range", "str", "continue", 12, True, "python", 3.14, "else"]
    
    longest_index = -1
    longest_length = -1
    
    for i in range(len(lst)):
        item = lst[i]
        if isinstance(item, str):
            if len(item) > longest_length:
                longest_index = i
                longest_length = len(item)
    
    if longest_index >= 0:
        print("Longest string: %s" % lst[longest_index] )
        print("Its' index: %s" % longest_index )
    else:
        print("No string")
    

    输出

    Longest string: continue
    Its' index: 2
    

    补充说明:由于并不确定列表第一项会不会是字符串。
    所以先定一个负值(比所有字符串最小值还要小的值)。
    方便找到字符串之后,用字符串去替换。

  • 相关阅读:
    Symbol Commands
    Control Structures
    script.stub
    Lowest Common Ancestor of a Binary Search Tree
    Move Zeroes
    Odd Even Linked List
    ubuntu18.04系统安装及php7.2,apache2,mysql8,git,svn,composer,vs code 到安装 php 扩展配置php.ini 实现 laravel5.8 运行
    thinkphp3.2.3 自定义路由实践
    thinkphp3.2.3 自动验证 unique 出错的解决办法
    【重磅】中国集成电路产业基金投资版图详解
  • 原文地址:https://www.cnblogs.com/BigShuang/p/15310179.html
Copyright © 2011-2022 走看看