zoukankan      html  css  js  c++  java
  • Python学习笔记(7):数据结构

    Python中有3中内建的数据结构——列表、元组和字典。

    1. 列表(List)

    列表用一对方括号[]表示,每项数据之间用逗号隔开。一旦你创建了一个列表,你可以对它进行添加、删除或搜索。所以列表是可以改变的。

    1)创建列表

    shoplist = ["apple", "mango", "carrot", "banana"]
    print("I have", len(shoplist), "items to purchase.")
    

    2)遍历

    for item in shoplist:
        print(item)
    

    3)添加数据

    print("I also have to buy rice.")
    shoplist.append("rice")
    print("My shopping list is now", shoplist)
    

    4)排序

    shoplist.sort()
    print("Sorted shopping list is", shoplist)
    

    5)检索

    print("The first item I will buy is", shoplist[0])
    

    6)删除数据

    olditem = shoplist[0]
    del shoplist[0]
    print("I bought the", olditem)
    print("My shopping list is now", shoplist)
    

    2. 元组

    元组和列表十分类似,只不过元组是不可以改变的,即不能被修改。元组是用一对圆括号()表示,每项数据之间也是用逗号隔开。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。

    zoo = ("wolf", "elephant", "penguin")
    print("Number of animals in the zoo is", len(zoo))
    
    new_zoo = ("monkey", "dolphin", zoo)
    print("Number of animals in the new zoo is", len(new_zoo))
    
    print("All animals in new zoo are", new_zoo)
    print("Animals brought from old zoo are", new_zoo[2])
    print("Last animal brought from old zoo is", new_zoo[2][2])
    

    元组有与列表一样的索引运算符。含有0个或1个项目的元组。一个空的元组由一对空的圆括号组成,如myempty = ()。然而,含有单个元素的元组就不那么简单了。你必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。即如果你想要的是一个包含项目2的元组的时候,你应该指明singleton = (2 , )。

    元组最通常的用法是用在打印语句中。

    age = 22
    name = "Swaroop"
    print("%s is %d years old" % (name, age))
    print("Why is %s playing with that python?" % name)
    

    %s表示字符串,%d表示整数。

    3. 字典(dict)

    字典是一个键值对集合,键必须是唯一的。注意,你只能使用不可变的对象(比如字符串)来作为字典的键,但是你可以把不可变或可变的对象作为字典的值。字典是用一对花括号{}表示,每个键值对之间用逗号隔开,键值之间用冒号分隔。

    1)创建字典

    ab = {"user1" : "user1@test.com", "user2" : "user2@test.com"}
    

    2)遍历

    for name, address in ab.items():
        print("Contact %s at %s" % (name, address))
    

    3)添加数据

    if not "tom" in ab:#OR not ab.has_key("tom")
        ab["Tom"] = "tom@test.com"
    

    4)检索

    print("user1's address is %s" % ab["user1"])

    5)删除

    del ab["tom"]
    

    4. 序列

    列表、元组和字符串都是序列,序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。

    #Indexing or "Subscription" operation
    print("Item 0 is", shoplist[0])
    print("Item -1 is", shoplist[-1])
    
    #Slicing on a list
    print("Item 1 to 3 is", shoplist[1:3])
    print("Item 2 to end is", shoplist[2:])
    print("Item 1 to -1 is", shoplist[1:-1])
    print("Item start to end is", shoplist[:])
    
    #Slicing on a string
    name = "known"
    print("charactor 1 to 3 is", name[1:3])
    

    索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的。因此,shoplist[-1]表示序列的最后一个元素而shoplist[-2]抓取序列的倒数第二个项目。

    切片操作符是序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。注意这与你使用的索引操作符十分相似。记住数是可选的,而冒号是必须的。
    切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。如果不指定第一个数,Python就从序列首开始。如果没有指定第二个数,则Python会停止在序列尾。注意,返回的序列从开始位置 开始 ,刚好在 结束 位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。

    5. 对象与引用

    print("Simple Assignment")
    shoplist = ['apple', 'mango', 'carrot', 'banana']
    mylist = shoplist # mylist is just another name pointing to the same object!
    del shoplist[0]
    print("shoplist is", shoplist)
    print("mylist is", mylist)
    # notice that both shoplist and mylist both print the same list without
    # the 'apple' confirming that they point to the same object
    
    print("Copy by making a full slice")
    mylist = shoplist[:] # make a copy by doing a full slice
    del mylist[0] # remove first item
    print("shoplist is", shoplist)
    print("mylist is", mylist)
    # notice that now the two lists are different
    

    输出结果:

    Simple Assignment
    shoplist is ["mango", "carrot", "banana"]
    mylist is ["mango", "carrot", "banana"]
    Copy by making a full slice
    shoplist is ["mango", "carrot", "banana"]
    mylist is ["carrot", "banana"]

    6. 字符串函数

    name = "Swaroop" # This is a string object
    if name.startswith("Swa"):
        print("Yes, the string starts with 'Swa'")
    
    if "a" in name:
        print("Yes, it contains the string 'a'")
    
    if name.find("war") != -1:
        print("Yes, it contains the string 'war'")
    
    delimiter = "_*_"
    mylist = ["Brazil", "Russia", "India", "China"]
    print(delimiter.join(mylist))
    

    输出结果:

    Yes, the string starts with 'Swa'
    Yes, it contains the string 'a'
    Yes, it contains the string 'war'
    Brazil_*_Russia_*_India_*_China

  • 相关阅读:
    ASP.Net Core MVC+Ajax 跨域
    ASP.Net Core MVC 发生二次请求
    Spire高效稳定的.NET组件
    ASP.Net Core Razor+AdminLTE 小试牛刀
    二维码神器QRCoder
    读入 并查集 gcd/exgcd 高精度 快速幂
    Codeforces 348 D
    Gym
    BZOJ 3894 文理分科 最小割
    BZOJ 2132 圈地计划 最小割
  • 原文地址:https://www.cnblogs.com/known/p/1817499.html
Copyright © 2011-2022 走看看