zoukankan      html  css  js  c++  java
  • python3-列表字典简单练习题

    1.求全部元素的和[1,2,1,2,3,3,3,3]
    >>> a=[1,2,1,2,3,3,3,3]
    >>> result=0
    >>> for i in a:
    ...     result+=i
    ...
    >>> print (result)
    18
    
    2.求偶数元素的和[1,2,1,2,3,3,3,3]    
    方法一:只适用于当前list
    >>> a=[1, 2, 1, 2, 3, 3, 3, 3]
    >>> res=0
    >>> for i in a[1:4:2]:
    ...     res+=i
    ...
    >>> print (res)
    4
    方法二:适用于任何list
    >>> a=[1, 2, 1, 2, 3, 3, 3, 3]
    >>> res=0
    >>> for i in a:
    ...     if i%2==0:
    ...        res+=i
    ...
    >>> print(res)
    4
    
    3.统计一下所有数字出现的个数[1,2,1,2,3,3,3,3]
    >>> d={}
    >>> for i in a:
    ...     d[i]="1"
    ...
    >>> d
    {1: '1', 2: '1', 3: '1'}
    >>> d.keys()
    dict_keys([1, 2, 3])
    >>> list(d.keys())
    [1, 2, 3]
    >>> for i in list(d.keys()):
    ...     print("数字"+str(i)+"共出现了:"+str(a.count(i))+"")
    ...
    数字1共出现了:2次
    数字2共出现了:2次
    数字3共出现了:4次
  • 相关阅读:
    构建之法阅读笔记05
    四元数(Quaternion)
    httpclient
    两种unity双击事件
    WWW网络请求
    Unity混合天空盒
    unity message
    unity射线检测
    unity 初始化数据存储问题
    Awake,start,update,OnEnable,OnDisable
  • 原文地址:https://www.cnblogs.com/ssj0723/p/10177605.html
Copyright © 2011-2022 走看看