zoukankan      html  css  js  c++  java
  • Python 列表与字典

    Python 列表与字典

    1 列表(Lists)

    列表其实就是Python的数组,它支持动态调整大小,并且可以包含不同类型的元素。

    a = []
    
    • 列表的常用方法包括count(key),index(value),reverse(),sort(),append(value),pop()

    • 切片操作:

    nums = list(range(5)) 
    print(nums) # [0, 1, 2, 3, 4]
    print(nums[2:4]) # [2, 3]
    print(nums[2:]) # [2, 3, 4]
    print(nums[:2]) # [0, 1]
    print(nums[:]) # [0, 1, 2, 3, 4]
    print(nums[:-1]) # [0, 1, 2, 3]
    nums[2:4] = [8, 9]
    print(nums) # [0, 1, 8, 9, 4]
    
    • 列表推导式
    nums = [0, 1, 2, 3, 4]
    even_squares = [x ** 2 for x in nums if x % 2 == 0]
    print(even_squares) # [0, 4, 16]
    

    1 字典(Map)

    Python中的字典类似于C++中的Map。

    d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data
    print(d['cat'])       # Get an entry from a dictionary; prints "cute"
    print('cat' in d)     # Check if a dictionary has a given key; prints "True"
    d['fish'] = 'wet'     # Set an entry in a dictionary
    print(d['fish'])      # Prints "wet"
    # print(d['monkey'])  # KeyError: 'monkey' not a key of d
    print(d.get('monkey', 'N/A'))  # Get an element with a default; prints "N/A"
    print(d.get('fish', 'N/A'))    # Get an element with a default; prints "wet"
    del d['fish']         # Remove an element from a dictionary
    print(d.get('fish', 'N/A')) # "fish" is no longer a key; prints "N/A"
    

    访问字典的方式

    d = {'person': 2, 'cat': 4, 'spider': 8}
    for animal, legs in d.items():
        print('{:s} has {:d} legs'.format{animal, legs})
    
    ---- suffer now and live the rest of your life as a champion ----
  • 相关阅读:
    让Android模拟器速度飞起来_Eclipse+BlueStacks调试Android应用【2012-10-30】
    开源镜像站-Android镜像
    字符编码的几篇文章
    [C/C++]_[Unicode转Utf8,Ansi转Unicode,Ansi文件转Utf8文件]
    MSVC下快速Unicode I/O
    edltplus使用正则表达式替换多余空行
    修改CMD的编码
    windows 安裝 gcc 編譯器
    CF369 C(递归 + 回溯)
    VIM支持系统剪切板
  • 原文地址:https://www.cnblogs.com/popodynasty/p/14539936.html
Copyright © 2011-2022 走看看