程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Those are great to use, but if they are not used well, they may be beaten by others

編輯:Python

Quickly store the two separately key and value Merge your list into a dictionary

>>> a = ["key1", "key2", "key3"]
>>> b = ["value1", "value2", "value3"]
>>> dict(zip(a, b))
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

The purpose of this operation is very common for crawler Engineers , for instance :

You need to collect some key value pair type information , Then you may encounter some platform interfaces that return these information directly. Only value A list of , also key Are written dead in code or request parameters , At this time, you can quickly merge them into a dictionary through this operation , In this way, it is more convenient to take values , The readability of the value part will also be much better .

Another situation is , You may encounter such key value pair information on some websites in HTML in key and value The element of is a horizontal relationship , also key and value There is no distinguishing mark , In these cases, we can only extract the elements of the whole key value pair and convert them into a list , Then, we take them out respectively by slicing them according to the subscript interval of the list key and value A list of , Then combine them into a dictionary . Such as this :

>>> result = ["key1", "value1", "key2", "value2", "key3", "value3"]
>>> result[0::2]
['key1', 'key2', 'key3']
>>> result[1::2]
['value1', 'value2', 'value3']
>>> dict(zip(result[0::2], result[1::2]))
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

It should be noted that , This operation runs into key and value When the quantity is inconsistent , It will automatically ignore the value at the end of the list , You need to make sure key and value It's right .

In a nutshell , If your key The list is better than value One more value in the list , Then the final dictionary will be missing key The last extra value in the list .

Press your head quickly 、 tail 、 Cut the element in the middle , And assign them to three variables

>>> a = "123456789" # It can also be list And so on.
>>> a1, *a2, a3 = a
>>> a1
'1'
>>> a2
['2', '3', '4', '5', '6', '7', '8']
>>> a3
'9'

The purpose of this operation , It should be common for crawler engineers or some back-end engineers who will be exposed to private protocols , for instance :

You may encounter some problems based on TCP or UDP A private agreement , Then they may define a header by the content type 、 Communication content 、 A structure composed of check codes and so on , I will return such a thing to you every time I communicate , Then you need to cut them and assign them to different variables , At this time, you can quickly achieve this effect through this operation .

Of course , This operation can't be used indiscriminately , You'd better make sure its content doesn't change , Like a private agreement , You can judge the protocol version number and so on , To ensure that its content must be this structure .

Quickly unzip the list containing nested lists , At the same time, the values in the nested list are assigned to different variables

>>> result = [1, 2, [3, 4], 5]
>>> [a, b, [c, d], e] = result
>>> a
1
>>> b
2
>>> c
3
>>> d
4
>>> e
5

This operation is also occasionally used when dealing with some private protocols , You can use this operation to quickly assign values in the list to different variables for processing , Very convenient .

If you only need to nest a value at the beginning of a list , What about the rest that don't need to be done ? It can be like this :

>>> result = [1, 2, [3, 4, 5]]
>>> [a, b, [c, *_]] = result
>>> a
1
>>> b
2
>>> c
3

In short, it is the same as the previous operation , Use asterisks to handle subsequent values , And assign them to temporary variables such as underscores .

notes : The purpose and meaning of underline variables can be searched by search engines , There are many articles on the Internet that mention , I won't go into that here .

When traversing nested lists of different lengths , Press the head 、 Tail cutting , And assign them to two variables

>>> result = [["items", "item1", "item2", "item3"], ["status", 1]]
>>> for key, *values in result:
... print(key)
... print(values)
...
>>> items
['item1', 'item2', 'item3']
>>> status
[1]

This operation is occasionally used when dealing with some private protocols or interfaces of exotic platforms , The content returned to you by the other party may be such a nested list , The first value of the sublist is key、 The back part is value, Then some wonderful platforms may not even have the same order of sub lists .

In this case, if you use this operation to get key and value Words , It will be much more convenient , You don't have to worry about it value How many in the world , There is no need to press the subscript 0 To get... In the nested list key, You just have to do this directly for Take a look and deal with key and value Just a matter of .

>>> {key:values for key, *values in result}
{'items': ['item1', 'item2', 'item3'], 'status': [1]}

You can even write this code directly on one line , Directly convert them into dictionaries for subsequent processing .

Quickly unzip a dictionary , And put it inside key and value We assign different values to different variables

>>> a = {"key1": "value1", "key2": "value2", "key3": "value3"}
>>> (key1, value1), (key2, value2), (key3, value3) = a.items()
>>> key1
'key1'
>>> value1
'value1'
>>> key2
'key2'
>>> value2
'value2'

The purpose of this operation is also common for crawler engineers and back-end Engineers , for instance :

You need to extract the status code returned by an interface 、 Status information and data The content of , And you need to judge whether the status code represents the successful request , At this time, if you pass one by one key DE value 、 Assignment will be troublesome , But if you use this operation , It can be solved quickly .

Maybe that's not intuitive , Look at a sample code :

>>> result = {"code": 200, "data": {"balabala": 111}, "msg": None}
>>> (_, code), (_, data), (_, msg) = result.items()
>>> code
200
>>> data
{'balabala': 111}
>>> msg
>>>

Of course, this operation can't be used indiscriminately , When using this operation , You need to make sure that key The order is strictly the same , Otherwise, the wrong content may be extracted , So before extraction, in order to prevent disorder , You can press key Make a sort , To ensure that the order is strictly consistent .

Then whether there will be any change in the content of the dictionary also needs to be considered , If your code needs to be very rigorous , Then just press key Take it one by one , After all, if there's one more key In the middle , What you get will be completely different .

Create functions dynamically

Sometimes you may encounter special situations like this : You have some different values that need to be handled in the same way , However, due to the limitation of conditions, you can't summarize this function into one and process it by passing parameters , You can only write out multiple functions with different names to handle .

Or you may simply have a requirement to dynamically create a temporary function to use .

At this time, if you use this operation , You can easily solve this problem , Just like this, you can dynamically create a function :

>>> from types import FunctionType
>>>
>>> func = FunctionType(compile(
... ("def func():\n"
... " print(1)\n"
... " return 2"),
... "<string>",
... "exec"
... ).co_consts[0], globals())
>>> print(func())
1
2

notes : The strings enclosed in parentheses will be spliced automatically , Belong to Python One of the ways to write multi line strings in , The advantage is that the string content will not be affected by indentation like three quotation marks . If you want to know more, you can check it yourself Python Official documents , The string part inside tells this little skill .

We can also dynamically generate the function code string inside ( For example, use format), To modify the function name and content , We can even use things like Jinja This template rendering library to achieve more convenient function code generation .

because Django Admin the action The parameters of the function are fixed , And if you need to pass it to action Function, you need to implement it through the middle page , And I don't want to get the middle page 、 There are several different parameters that need to be handled separately , So we directly use the way of dynamically creating functions to solve .

Dynamic import

Sometimes you may have some extension code that needs to be imported dynamically at run time , Then you can use this operation , For example, we need to import operator This library :

>>> import importlib
>>>
>>> module = importlib.import_module("operator")

And then this module The variable is the name of the imported module , We can use it directly as in normal import , For example, we need to call its add function :

>>> module.add(1, 1) # The addition operator
2

Dynamic invocation

Sometimes after dynamic import , You also need to make dynamic calls , Then you can do this :

>>> import importlib
>>>
>>> module = importlib.import_module("operator")
>>> func = getattr(module, "add")
>>> func(1, 1)
2

Of course , When using dynamic creation 、 Dynamic import 、 This comparison is called dynamically Hack During the operation of , Be sure to pay attention to safety , If you need to input some parameters when using , Be sure to check the input , So as not to be used to directly execute dangerous code .

For example, you provide a function to dynamically create functions , If you don't check the content , Maybe some bad people just go through os Library and so on to call the command line and hack your machine , Very dangerous .

So that's all for this sharing , In fact, there are many operations about these coquettish , If you are interested, you can pay more attention to the code written by others and various forums , Sometimes there will be some unexpected gains .

 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved