zoukankan      html  css  js  c++  java
  • Python学习笔记——基本数据结构

    列表list

    List是python的一个内置动态数组对象,它的基本使用方式如下:

        shoplist = ['apple', 'mango', 'carrot', 'banana']

        print 'I have', len(shoplist),'items to purchase.'

        print 'These items are:', # Notice the comma at end of the line
        for item in shoplist:
            print item,


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

        print 'I will sort my list now'
        shoplist.sort()
        print 'Sorted shopping list is', shoplist

        print 'The first item I will buy is', shoplist[0]
        olditem = shoplist[0]
        del shoplist[0]

        print 'I bought the', olditem
        print 'My shopping list is now', shoplist

     

    元组Tuple

    Python的typle通过小括号初始化,是一个只读对象。不过它的成员具有数组的访问方式。

        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]

     

    字典dict

    Dict是一个查询式的数据结构,它的基本用法如下:

    ab = {    'Swaroop' : 'swaroopch@byteofpython.info',
            'Larry' : 'larry@wall.org',
            'Matsumoto' : 'matz@ruby-lang.org',
            'Spammer' : 'spammer@hotmail.com'
            }

    print "Swaroop's address is %s" % ab['Swaroop']

    # Adding a key/value pair
    ab['Guido'] = 'guido@python.org'

    # Deleting a key/value pair
    del ab['Spammer']

    print ' There are %d contacts in the address-book ' % len(ab)
    for name, address in ab.items():
        print 'Contact %s at %s' % (name, address)

    if 'Guido' in ab: # OR ab.has_key('Guido')
        print " Guido's address is %s" % ab['Guido']

     

  • 相关阅读:
    深入理解JS中的变量及变量作用域
    浏览器加载、解析、渲染的过程
    gerrit和git
    宽高等比缩放
    常见的网站性能优化手段
    JS实现数组去重(重复的元素只保留一个)
    重构与回流
    APP开放接口API安全性——Token令牌Sign签名的设计与实现
    索引原理-btree索引与hash索引的区别
    从四个维度谈谈如何做好团队管理
  • 原文地址:https://www.cnblogs.com/TianFang/p/3215294.html
Copyright © 2011-2022 走看看