zoukankan      html  css  js  c++  java
  • Python 简说 list,tuple,dict,set

    python 是按缩进来识别代码块的 。

    缩进请严格按照Python的习惯写法:4个空格,不要使用Tab,更不要混合Tab和空格,否则很容易造成因为缩进引起的语法错误。

    list  有序集合  访问不可越界

    L = [] #定义空集合
    
    L = [12, 'China', 19.998] #定义集合
    
    print (L[0]) #打印第一个元素
    
    print (L[-1]) #打印倒数第一个元素
    
    L.append('Jack') #尾部追加
    
    L.insert(1, 3.14) #指定位置追加
    
    L.pop() #尾部弹出
    
    L.pop(0) #指定位置弹出
    
    L[1] = 'America' #指定位置重新定义
    View Code

    Tuple 不可修改  访问不可越界

    t = ()  #创建
    
    t = ("nihao",)  #为避免直接输出nihao,需要加上‘,’
    
    t = ("nihao", "hello") #定义tuple
    
    t = (3.14, 'China', 'Jason', ['A', 'B']) #A,B 可变
    View Code

    Dict   Key-Value键值对    Key不存在,会报错     Dict是无顺序的   Key不可变,Value可变。

              查找速度快。无论是10个还是10万个,速度都是一样的,但是代价是耗费的内存大

    d = {'Lisa': 85, 'Paul': 75, 'Adam': 95, 'Bart': 59}  #定义
    
    len(d)  #元素数量
    
    print (d['Jone'])  #访问,不存在会报错
    
    print (d.get('Adam')) #访问,不存在不会报错的,返回None
    
    d['Jone'] = 99  # 有则替换,没有则添加
    View Code

    set  无序  元素不可重复

    s = set([1, 2, 3]) #定义
    
    s.add(4) #添加,如果已经存在不会重复添加
    
    s.remove(4) #移除,如果不存在会报错
    View Code

    if elseif 

    if 语句后接表达式,然后用:表示代码块开始。

    age = 20
    if age >= 18:
        print 'your age is', age
        print 'adult'
    print 'END'
    View Code

    for 这样一来,遍历一个list或tuple就非常容易了

    L = ['Adam', 'Lisa', 'Bart']
    
    for name in L:
        print name
    View Code

    while

    #while循环每次先判断 x < N,如果为True,则执行循环体的代码块,否则,退出循环
    N = 10
    x = 0
    while x < N:
        print x
        x = x + 1
    View Code

    break是结束整个循环体,continue是结束单次循环

  • 相关阅读:
    SpringBoot+SpringCloud
    bootstrap-thymeleaf-分页
    排序-Java
    native2ascii运用
    标准W3C盒子模型和IE盒子模型
    在既定状态下截图
    java.util.zip.ZipException: error in opening zip file
    安装 haproxy
    mysql集群
    最简redis集群配置
  • 原文地址:https://www.cnblogs.com/zhaoyang-1989/p/7095026.html
Copyright © 2011-2022 走看看