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

no You can learn a python trick in 30 seconds?!

編輯:Python

Hello, everyone ! I'm a panda

A lot of learning Python Our friends will encounter many problems in the realization of functions in the actual project , Some problems are not very difficult , Or there is a good way to solve it . Of course , Which makes perfect , When we are proficient in code , Naturally, we can sum up some useful skills , But for those who are just familiar with Python Our classmates may not be so relaxed .

This time I recommend a good resource to learn these skills “30-seconds-of-python”, All techniques and methods as long as 30 In seconds get To , You can use your business time to accumulate . Let's take a quick look at .

https://github.com/30-seconds/30-seconds-of-python

1. Content catalog

Here is 30 Secology Python The entire catalog of , It is divided into several parts :List、Math、Object、String、Utility, Here is the brain map of the mind .


what are you having? python I won't answer the related error report 、 Or source code information / Module installation / Women's clothing bosses are proficient in skills   You can come here :(https://jq.qq.com/?_wv=1027&k=2Q3YTfym) Or the private number at the end of the text

I chose 10 A practical and interesting way to share , The rest of you can learn by yourself .

1. List:all_equal

Function realization : Verify that all elements in a list are the same .

Reading : Use [1:] and [:-1] To compare all elements of a given list .

def all_equal(lst):
return lst[1:] == lst[:-1]

give an example :

all_equal([1, 2, 3, 4, 5, 6]) # False
all_equal([1, 1, 1, 1]) # True

2. List:all_unique

Function realization : If all values in the list are unique , return True, otherwise False

Reading : Use set... On a given list set() duplicate removal , Compare it with the length of the original list .

def all_unique(lst):python Learn to exchange skirts :660193417###
return len(lst) == len(set(lst))

give an example :

x = [1,2,3,4,5,6]
y = [1,2,2,3,4,5]
all_unique(x) # True
all_unique(y) # False

3. List:bifurcate

Function realization : Group list values . If in filter The element is True, So the corresponding element belongs to the first group ; Otherwise it belongs to the second group .

Reading : Use list derivation and enumerate() be based on filter Elements to groups .

def bifurcate(lst, filter):
return [
[x for i,x in enumerate(lst) if filter[i] == True],
[x for i,x in enumerate(lst) if filter[i] == False]
]

give an example :

bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True])
# [ ['beep', 'boop', 'bar'], ['foo'] ]

4. List:difference

Function realization : Return to two iterables Differences between .

Reading : establish b Set , Use a The list derivation of is not in _b The elements in .

def difference(a, b):
_b = set(b)
return [item for item in a if item not in _b]

give an example :

difference([1, 2, 3], [1, 2, 4]) # [3]

5. List:flatten

Function realization : One off consolidated list .

Reading : Use nested lists to extract each value of a sublist .

def flatten(lst):
return [x for y in lst for x in y]

give an example :

flatten([[1,2,3,4],[5,6,7,8]]) # [1, 2, 3, 4, 5, 6, 7, 8]

6. Math:digitize

Function realization : Decompose a number into digits .

Reading : take n Use... After charring map() Function combination int Complete the transformation

def digitize(n):
return list(map(int, str(n)))

give an example :

digitize(123) # [1, 2, 3]

7. List:shuffle

Function realization : Randomly shuffle the list elements .

Reading : Use Fisher-Yates Algorithm reorders list elements .

from copy import deepcopy
from random import randint def shuffle(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while (m):
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst

give an example :

foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]

8. Math:clamp_number

Function realization : The digital num The clamp is made by a and b In the range specified by the boundary value .

Reading : If num To the full extent , return num; otherwise , Returns the closest number in the range .

def clamp_number(num,a,b):
return max(min(num, max(a,b)),min(a,b))

give an example :

clamp_number(2, 3, 5) # 3
clamp_number(1, -1, -5) # -1

9. String:byte_size

Function realization : Returns the number of bytes in the string .

Reading : Use string.encode(‘utf-8’) Decode the given string , Return length .

def byte_size(string):
return len(string.encode('utf-8'))

give an example :

byte_size('') # 4
byte_size('Hello World') # 11

10. Math:gcd

Function realization : Calculate the greatest common factor of several numbers .

Reading : Use reduce() and math.gcd Implement... On a given list .

from functools import reduce
import math def gcd(numbers):
return reduce(math.gcd, numbers)

give an example :

gcd([8,36,28]) # 4

That's all 30 Secology python All kinds of tricks . What about? , Is there any new inspiration for some common operations , besides , There are many other skills that you can learn slowly , I hope it will help you .

https://github.com/30-seconds/30-seconds-of-python

I'm a panda , See you in the next article (*◡‿◡)

Isn't it ?30 second You can learn one python Tips ?! More articles about

  1. Python Learning notes 4- How to quickly learn a Python Module 、 Method 、 keyword

    Want to learn one quickly Python Modules and methods of , Two functions have to know , That's it dir() and help() dir(): It can quickly list all the contents of the module in the form of set ( class . Constant . Method ) example : #--encoding: ...

  2. Primary school students can learn python( Small data pools )

    Primary school students can learn python( Small data pools ) 1. Small data pools . Purpose : Cache our strings , Integers , Boolean value . There is no need to create too many objects when using cache :int, str, bool. int: Cache range -5~256 ...

  3. Day1: first python Applet

    Day1: first python Applets and development tools Pycharm One .Hello World C:\Users\wenxh>python Python 3.6.2 (v3.6.2:5fd33b5, J ...

  4. first python Little script

    first python A little experiment Preface As a job 1 Year of linux Operation and maintenance brick movers , It's really hard to get along without some development ability . So I made up my mind to study python! Go directly to the sentence just written ( Don't despise the great God ) Enter an account password through the console , ...

  5. dos Interface java File error output to a text tip

    If dos perform java There is an error , Log errors to a document When it's right, it's like this , The output is hello, I put String Of s Change to lowercase , There is an error , use 2> Command output to error.txt In the current directory error. ...

  6. [ One a day Linux Tips ] gdb Run multiple commands next time

    commonly gdb When it's running , We can only enter a command . Such as : (gdb) c (gdb) bt Suppose you want to run multiple commands ? Can it be like bash like that , Use ; Such as ls; ls The conclusion is no . But it can pass gdb The built-in ...

  7. Publish a Python Applet :ManHourCalendar

    What happened when the program was born Let's talk about the background files first .. About two years ago , I went to the island country alone to earn some extra money . In the dispatch system over there , There is a concept about standard working hours per month , According to your company and the target company ( The industry calls it site ) Contract of , Specifies the ...

  8. A simple trick to achieve mobile access .html File web page effect

    Register login Github Don't explain settings Set pull down Select a theme and upload the code file to code Open this file and select the URL at this time Add... In front of the website This code http://htmlpreview.github.i ...

  9. first Python Little reptile

    This reptile is a reference http://python.jobbole.com/81353/ This article is about This article may be too old , So some codes will report errors , Then I modified it a little , Added one getContentAll ...

  10. 【 turn 】 My first one Python Applet

    Original website :http://blog.csdn.net/randyqiu/article/details/4484089 Every first time has a special meaning , So the following little program, I record it as a souvenir . Because ...

Random recommendation

  1. understand JavaScript Medium “this”

    about javascript For beginners , General pair “this” Keywords are very confused . The purpose of this article is to give you a comprehensive understanding of “this”, Understand how to use... In every situation “this”, I hope that through this article , It can help students not to be afraid “t ...

  2. Sage Crm Analysis of authority principle

    Words are 11 Year written , Post it and share it , Let's start with a table structure : One . Area . Table name :[territories] 1. Let's first look at the structure of the region table . From the figure, there are fields that cannot be empty in front , It's all very important . Let's introduce these fields : Te ...

  3. Flash Animation

    Flash ( Interactive vector graphics and Web Animation standards ) Flash By macromedia Interactive vector graphics and Web The standard of animation , from Adobe Male The company acquired . do Flash Animators are called flashers . Web designers use ...

  4. 100735G

    Obviously , We construct a post string , It's just two results : The longest one is black , The longest one is white , So just choose two small ones #include<iostream> using namespace std; int ...

  5. Interface testing has never been easier - Postman (Chrome plug-in unit )

    Interface testing has never been easier - Postman (Chrome plug-in unit ) A very powerful Http Client Tools are used to test Web Service , Let me introduce how to use it to test restful web service notes : Reprint ...

  6. ADF_Starting series 1_JDeveloper IDE Introduction to the development environment

    2013-05-01 Created By BaoXinjian

  7. Android:Error:Execution failed for task &#39;:app:transformResourcesWithMergeJavaResForDebug&#39;.

    Development today Android Project time , Imported http About shelf bag , The program compilation error is as follows : Error:Execution failed for task ':app:transformResourcesWithMe ...

  8. CSAPP- Procedure call , data storage , out of buffer

    Program compilation : 1. Pretreatment stage : 1. File contains : take #include Expand to document body 2. Conditional compilation : according to #if and #ifdef Exclude or include a part of the program 3. Macro expansion : Expand the place where the macro reference appears into the corresponding macro 2. Compile level ...

  9. poj3237 Tree chain part Edge weight template

    Tree Time Limit: 5000MS   Memory Limit: 131072K Total Submissions: 7384   Accepted: 2001 Description ...

  10. Mysql View connections , state Maximum number of concurrent ( Fabulous )

    Mysql View connections , state Maximum number of concurrent ( Fabulous )   -- show variables like '%max_connections%'; See the maximum number of connections set global max_connect ...


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