The path of Python-day3

Source: Internet
Author: User
Tags shallow copy

Dictionary

Dic{key:value}

Meta-group
Similar to a list, the only thing that cannot be modified

DIC = {' name ': ' Alex ', ' age ': 18}
Inquire
Print (dic[' name ']) #会报错
Get method query, after query, if not included, will not error, return none
Print (Dic.get (' name '))
Increase
dic[' gender '] = ' lwq '
Print (DIC)
The elements in the dictionary are unordered, and the dictionary is worth finding by key.
Change
dic[' name '] = ' DT '
Dictionaries cannot be changed to key, only value
Delete
Del dic[' name ']
Definition rules for key:
1. Must be immutable. How to tell if the data type is mutable: First define, look at the ID, then redefine, look at the ID, if the ID becomes variable, the ID is immutable (number, string, tuple), the expression is immutable (change the elements in the list, the dictionary),
name = ' Lwq ' name = ' HSC '
2. As long as you can hash, you can be a key,hash if you can define it as a key
3. The key in the dictionary is unique.
Value definition: All can
Dictionary definitions:
DIC3 = Dict ()
Dic4 = dict ({' name ': ' Alex ', ' age ': 18})
DIC5 = Dict (name= ' Alex ', age=18)
DIC6 = Dict ((' Name ', ' Ale '), (' age ', 18))

Dic1 = Dic.copy ()
Dic2 = Dict.fromkeys (' Hello ', 1) #快速生成字典, can put a list, string. It has nothing to do with the stated dictionary. When value is {}
Dic2 = Dict.fromkeys (' hell ', {}) if it is added again, {} will be occupied by an element,
DIC = Dict.fromkeys ('Hello', 1)Print(DIC) Dic1= Dict.fromkeys ('haha')Print(DIC1) Dic2= Dict.fromkeys ('name',{})Print(dic2) dic2['a'] ='b'Print(dic2) dic2['e'] = {'C': 1}Print(DIC2)


Dic.get (' name ') # dic[' name ')
Print (Dic.items ()) #项目, becomes a list, the list is a tuple
Dic.keys () #取字典中所有的key
Dic.pop (' name ') #删除, must exist to delete
Dic.popitem () #随机删除, no parameters required
Dic.setdefault (' Gender ', ' male ') #增加
#或者 Dic.setdefault (' Gender ', [])
Dic1 = {' Haah ': ' 111 ', ' name ': ' Lwq '}
Dic.update (DIC1) # can also be used as a modification to update with a new dictionary
Dic.values () #取字典的value

For I in DIC
Print (i) is a dictionary of all key


Shallow copy:
Copy only the first layer
Deep copy:
Import Importing Module
Import Copy
DIC3 = copy.deepcopy () deep copy

DIC10 = {' name ': ' HSC ', ' age ': {' lwq ': +, ' wt ': 20}}
Print (dic[' age ' [' Lwq '])


Differentiate by number of stored values

Scalar/Atomic Type Number, string
Container type list, tuple, dictionary

By Variable immutable distinction

Variable List, dictionary
Not variable Numbers, strings, tuples

Differentiate by Access order

Direct access Digital
Sequential access (sequence type) String, list, tuple
Key value access (mapping type) Dictionary

 

 collection: Resolving relational and deduplication 
Definitions: consists of different elements, which, if duplicated, are removed and the collection is not required.
S1 = {' A ', 1,2,3,4,5,4,4,4,}
Print (S1)

The relational operation of the collection
Python_set = {' Lwq ', ' HSC ', ' wt '}
Linux_set = {' ls ', ' Lwq ', ' HSC ', ' LMZ '}
ask for two set intersection
Print (python_set&linux_set)-------print (Python_set.intersection (linux_set )

, which contains all elements
Print (Python_set|linux_set)-------print (Python_set.union (linux_set))
Difference set
Print ( Python_set-linux_set) #去掉与linux_set相同的元素, print Python_set
Print (python_set.difference (linux_set))
Symmetric difference set
Print (Python_set^linux_set)------Print (Python_set.symmetric_difference (linux_set))
Subset
Print (Python_ Set.issubset (Linux_set))
Parent set
Print (Python_set.issuperset (linux_set))

#增加
S1.update (' e ')
S1.update (S5)
S1.update (' hello ') #把hello拆开加进去
S1.add (' hello ') #整体加进去
S1.pop () #随机删
S1.remove (' W ') #删除不存在的元素, error
S1.discard (' W ') # Delete non-existent elements without error
S1.copy () #浅拷贝
S1.clear ()
S1.difference_update (S5) #求差集并更新
S1.isdisjoint ()

Character encoding

First we define a memory variable in the terminal: name= ' lamb ', that memory variable is stored in memory (necessarily binary), so a code is required, Unicode (fixed in memory using character encoding is Unicode)

But if we write to the file Name= ' lamb ' saved to the hard disk (necessarily binary), also need a code, which is related to each country, if we use GBK, then the file is saved to the hard disk in GBK form .

Program to run: Hard disk binary (GBK)---> memory binary (Unicode)
That is, all programs eventually have to be loaded into memory, the program is saved to the hard drive in different countries in different encoding formats, but into memory we are in order to be compatible with all nations (the computer can run any country's program because of this), unified and fixed using Unicode, This is why memory is fixed with Unicode, you may say compatible with all nations I can use utf-8 ah, can, fully functional, the reason is not sure that Unicode is more efficient than utf-8 AH (uicode fixed with 2 byte encoding, utf-8 need to calculate), But Unicode is a waste of space, yes, this is a way to use space for time, and storage to the hard disk, or network transmission, all need to turn Unicode into utf-8, because the transmission of data, the pursuit of stability, efficiency, the smaller the amount of data transmission is more reliable, They are then converted to UTF-8 format instead of Unicode.


Gbk->unicode need decode (), UNICODE->GBK need encode () that's what this means.

When you browse the Web, the server converts dynamically generated Unicode content to UTF-8 and then to the browser

Python program is very special, want to run the Python interpreter to call, it is equivalent to the Python interpreter to read the memory of the program's Unicode code

Thus the Python interpreter also has an interpreter default encoding can be viewed with sys.getdefaultencoding (), if not the Python file specifies header information #-*-coding:utf-8-*-, then use the default

Note that this code is the code for the Python interpreter software.

Summary

In fact, whether it is word or pycharm, Python interpreter, we can when they are processing files software

Attention:

    • python2.7 interpreter is encoded as ASCII by default
    • PYTHON3.5 interpreter is encoded as UTF-8 by default
    • Whether it's a Python interpreter or any other text-related software, they can only specify the character encoding that accesses the file to the hard disk, and the memory is fixed using the Uniccode
    • The header of the test.py file is the #-*-coding:utf-8-*-that modifies the Python interpreter's encoding.

Process:

    1. The binary bytes type data from the hard disk read-test.py is loaded into memory, and now the Python interpreter is a class of word software, and the Python interpreter has its own encoding to decode the binary of the file into Unicode into memory
    2. The Python interpreter reads Unicode code interpretation execution from memory, and the code specified by the function does not have any relation to the Python interpreter.
 High Voltage: 1 
Low voltage: 0
Character------------------the process of translating-------〉〉 number
ASCII--------8-bit 2-binary represents a character
GBK-------- The 16-bit binary represents a Chinese character
Unicode universal code
Utf-8 variable length chinese with three bytes, English with a byte
defined variable to memory, you must use Nicode encoding
hard disk---------〉〉 character
Character--- Unicode-----〉〉 Memory Fixed
Encode encoding decode decoding

1. Memory is fixed using Unicode encoding, hard disk encoding (software that can be modified)
2. What encoding to use to read the hard disk.
3. The program runs in two stages: 1. read from hard disk to memory 2.python interpreter run a program that has read to memory
4. For a. py file, Python differs from pycharm\netepad++ by the second step of
5. The head of the file indicates that the interpreter is to be interpreted in that way.


File processing

f = open (' My ', ' W ')   #w创建写模式, if present, overwrite  a append write mode   r Read-only mode
F.write (' I love Beijing ' + ' \ n ')
F.close () #保存
#del只能删除内存对象, you can't delete something on your hard drive.
#混合模式
#读写: w+ write and read the contents, then go to the operation
# + Append, read append to last
# r+ Read and write add content to the first line and overwrite the first row of content
F.close () #判断文件是否关闭
Print (f.encoding) #打印文件编码
Print (F.fileno ()) #文件在操作系统中的索引值
F.flush () #强制刷新文件 (Save)
F.isatty () #判断是否是一个终端
F.name #打印文件名
F.readable () #不可读的, make judgments
F.seek () #寻找 Move the cursor to the tenth character and print the contents later
F.seekable () #是否可寻找
F.tell () #告诉当前光标的位置
F.truncate () #截断 interrupts the contents from the position of the cursor, the contents of which are not displayed (processing binaries), can be specified in size, and start from the beginning.
date = [' alex\n ', ' lwq\n ']
F.writelines (date) #将列表按行插入文件

To modify a file:
1. Write all memory
2 take up hard disk resources, modify and delete the original version.
    First, if it is not the content to be modified, write directly to the new file
If you want to modify the content, write the new file after the modification
Need to open two files at the same time, read from one file, and then write another file
To modify the contents of a file:
f = open ('myname','R', encoding='Utf-8') F_new= Open ('myname_new','W', encoding='Utf-8') forLineinchF:if 'listen to the radio often' inchLine:line= Line.replace ('listen to the radio often','watch TV series often') F_new.write (line) F.close () f_new.close ()

Handle large files: You can read a line, delete a row, so that the memory is only one row.
For line in F:
Print (line)
If you write in this way, the next time you read the file, the cursor is still at the beginning of the first line.
F.read (5) indicates read-only five


The file read can only be read one change, if you want to read the second time you must move the cursor over it.

Print progress bar: Flush based
Import Sys,time
For I in range (20):
Sys.stdout.write ("#")
Sys.stdout.flush ()
Time.sleep (0.1)


Eval (date) #将字符串转换成字典

sys.argv
import sys
is to import the entire "sys" module. I do not know that the mention of the C + + has not learned, and their "#include" similar:
You include the iostream to system to your std::cout, you import the SYS, you can use the system to your SYS.ARGV.

And then say argv this variable again.
"argv" is a shorthand form of the "argument variable" parameter variable, which is typically passed to the program by the system at the command line invocation.

This variable is actually a list, argv[0] is generally called the script file name or full path, and the operating system, argv[1] and later is the incoming data.

Then we'll look at the command line that invokes the script:
python using_sys.py We are arguments
Python, needless to say, "using_sys.py" script name, followed by a space separated by the "we""are""argument" is the parameter.
PS. General parameters are separated by a space, if there is a space inside the parameter to use double quotation marks, for example:
python using_sys.py hi "I ' m 7sDream"



The path of Python-day3

Related Article

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.