Nested dictionaries and collections practice examples

Source: Internet
Author: User

Nested dictionary exercises:
Av_catalog = {    "Europe":{        "www.youporn.com": ["a lot of free, the world's largest","General Quality"],        "www.pornhub.com": ["a lot of free, and it's big .","higher quality than Yourporn"],        "letmedothistoyou.com": ["Many are selfies, high-quality pictures a lot","not much resources, slow update"],        "x-art.com":["It's high quality, really high .","full charge, Dick than please bypass"]    },    "Japan and South Korea":{        "Tokyo-hot":["the quality is not clear, the individual already did not like Japan and Korea fan","I hear it's a charge."]    },    "Mainland":{        "1024x768":["It's all free, it's good, the good guys are safe","servers in foreign countries, slow"]}}av_catalog["Mainland"]["1024x768"][1] + =", you can crawl down with crawlers."Print(av_catalog["Mainland"]["1024x768"])#ouput['It's all free, it's good, the good guys are safe','server is abroad, slow, can crawl down with crawlers']
View Code

Collection of Exercises:

s = set ([3,5,9,10])#create a collection of valuesT= Set ("Hello")#Create a collection of unique charactersa= T | S#the set of T and Sb= T & S#intersection of T and SC= T–s#differential Set (items in T, but not in s)D= T ^ s#symmetric difference sets (items in t or S, but not both)Basic operation: T.add ('x')#Add an itemS.update ([10,37,42])#adding multiple items in Suse Remove () to delete an item: T.remove ('H'Len (s) set length xinchs tests if X is a member of S X not inchs tests if X is not a member of S S.issubset (t) s<=T Test if every element in S is in T S.issuperset (t) s>=T Test if every element in T is in S s.union (t) s|T returns a new set containing each element in S and T S.intersection (t) s&T returns a new set containing the common elements in S and T S.difference (t) s-T returns a new set containing an element in s but not in T S.symmetric_difference (t) s^T returns a new set containing a non-repeating element in S and T S.copy () returns a shallow copy of the set "s"
View Code

Open File Operation:

Somehow, it seems the love I knew was always the most destructive kind不知为何,我经历的爱情总是最具毁灭性的的那种Yesterday when I was young昨日当我年少轻狂The taste of life was sweet生命的滋味是甜的As rain upon my tongue就如舌尖上的雨露I teased at life as if it were a foolish game我戏弄生命 视其为愚蠢的游戏The way the evening breeze就如夜晚的微风May tease the candle flame逗弄蜡烛的火苗The thousand dreams I dreamed我曾千万次梦见The splendid things I planned那些我计划的绚丽蓝图I always built to last on weak and shifting sand但我总是将之建筑在易逝的流沙上I lived by night and shunned the naked light of day我夜夜笙歌 逃避白昼赤裸的阳光And only now I see how the time ran away事到如今我才看清岁月是如何匆匆流逝Yesterday when I was young昨日当我年少轻狂So many lovely songs were waiting to be sung有那么多甜美的曲儿等我歌唱So many wild pleasures lay in store for me有那么多肆意的快乐等我享受And so much pain my eyes refused to see还有那么多痛苦 我的双眼却视而不见I ran so fast that time and youth at last ran out我飞快地奔走 最终时光与青春消逝殆尽I never stopped to think what life was all about我从未停下脚步去思考生命的意义And every conversation that I can now recall如今回想起的所有对话Concerned itself with me and nothing else at all除了和我相关的 什么都记不得了The game of love I played with arrogance and pride我用自负和傲慢玩着爱情的游戏And every flame I lit too quickly, quickly died所有我点燃的火焰都熄灭得太快The friends I made all somehow seemed to slip away所有我交的朋友似乎都不知不觉地离开了And only now I‘m left alone to end the play, yeah只剩我一个人在台上来结束这场闹剧Oh, yesterday when I was young噢 昨日当我年少轻狂So many, many songs were waiting to be sung有那么那么多甜美的曲儿等我歌唱So many wild pleasures lay in store for me有那么多肆意的快乐等我享受And so much pain my eyes refused to see还有那么多痛苦 我的双眼却视而不见There are so many songs in me that won‘t be sung我有太多歌曲永远不会被唱起I feel the bitter taste of tears upon my tongue我尝到了舌尖泪水的苦涩滋味The time has come for me to pay for yesterday终于到了付出代价的时间 为了昨日When I was young当我年少轻狂

Basic operations

12345678 =open(‘lyrics‘#打开文件first_line =f.readline()print(‘first line:‘,first_line) #读一行print(‘我是分隔线‘.center(50,‘-‘))data = f.read()# 读取剩下的所有内容,文件大时不要用print(data) #打印文件f.close() #关闭文件

The mode of opening the file is:

    • R, read-only mode (default).
    • W, write-only mode. "unreadable; not exist; create; delete content;"
    • A, append mode. "Readable; not exist" create; "only append content;"

"+" means you can read and write a file at the same time

    • r+, can read and write files. "readable; writable; can be added"
    • w+, write and read
    • A +, with a

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading

    • RU
    • R+u

"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)

    • Rb
    • Wb
    • Ab

Other syntax

    def close (self): # real signature unknown;                Restored from __doc__ "" "Close the file.  A closed file cannot is used for further I/O operations.        Close () May is called more than once without error. "" "Pass Def Fileno (self, *args, **kwargs): # Real signature Unknown" "" Return the underlying file descr Iptor (an integer).  "" "Pass Def Isatty (self, *args, **kwargs): # Real signature Unknown" "" True if the file was connected to A TTY device. "" "Pass Def Read (self, size=-1): # known case of _io.                Fileio.read "" "Note that you may not be able to read it all back. Read at the most size bytes, returned as bytes.        Only makes one system call, so less data is returned than requested.        In non-blocking mode, returns None if the data is available.        Return an empty bytes object at EOF. "" "" Return "" Def readable (self, *args, **kwargs): # Real signature Unknown "" "True If File is opEned in a read mode. "" "Pass Def ReadAll (self, *args, **kwargs): # Real signature Unknown '" "" Read all data from the F                Ile, returned as bytes.  In non-blocking mode, returns as much as are immediately available, or None if no data is available.        Return an empty bytes object at EOF. "" "Pass Def Readinto (self): # real signature unknown;        Restored from __doc__ "" "Same as Rawiobase.readinto ()." "" Pass #不要用, no one knows what it's for. Def seek (self, *args, **kwargs): # Real signature Unknown "" "Move to new file posit                Ion and return the file position.  Argument offset is a byte count. Optional argument whence defaults to Seek_set or 0 (offset from start of file, offset should be >= 0); Other values is seek_cur or 1 (move relative to current position, positive or negative), and seek_end or 2 (move relative to end of file, usually negative, although many platforms allow SEeking beyond the end of a file).        Note that not all file objects is seekable. "" "Pass Def seekable (self, *args, **kwargs): # Real signature Unknown" "" True if file supports Random-a Ccess.                "" "Pass Def Tell (self, *args, **kwargs): # Real signature Unknown '" "" Current file position.        Can raise oserror for non seekable files.  "" "Pass def truncate (self, *args, **kwargs): # Real signature unknown '" "truncate the file to at                Most size bytes and return the truncated size.        Size defaults to the current file position, as returned by Tell ().        The current file position was changed to the value of size. "" "Pass Def writable (self, *args, **kwargs): # Real signature Unknown" "" True if file is opened in a W Rite mode. "" "Pass Def write (self, *args, **kwargs): # Real signature Unknown '" "" Write bytes B to file, ret Urn NumbEr written.        Only makes one system call, so is not all of the data is written.  The number of bytes actually written is returned.        In non-blocking mode, returns None if the write would block. "" "Pass

With statement

To avoid forgetting to close a file after opening it, you can manage the context by:

123 with open(‘log‘,‘r‘) as f:        ...

This way, when the with code block finishes executing, the internal automatically shuts down and frees the file resource.

After Python 2.7, with also supports the management of multiple file contexts simultaneously, namely:

12 with open(‘log1‘) as obj1, open(‘log2‘) as obj2:    pass

Nested dictionaries and collections practice examples

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.