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

Data analysis using Python -- function part

編輯:Python

List of articles

  • 1 Basic knowledge of
    • 1.1 Namespace
    • 1.2 Return multiple values
    • 1.3 Functions are also objects
  • 2 Some important functions
    • 2.1 map() function
    • 2.2 Anonymous functions (lambda)
    • 2.3 list() function
    • 2.4 set() function
    • 2.5 sort() Method

1 Basic knowledge of

  1. Function USES def Keyword declaration , use return Keyword return value .
def my_function(x, y, z=1.5):
if z > 1:
return z * (x + y)
else:
return z / (x + y)
  1. Can have multiple at the same time return sentence , If you don't encounter... When you reach the end of the function return, Then return to None.( and c The language is different )

  2. Functions can have some positional arguments ( Do not specify a default value ) And keyword parameters ( Specify default ).
    however , Keyword parameter must be in positional parameter ( If any ) after .

my_function(5, 6, z=0.7)
my_function(3.14, 7, 3.5)
my_function(10, 20)
my_function(x=5, y=6, z=7)
my_function(y=6, x=5, z=7)

1.1 Namespace

Function can access variables in two different scopes : overall situation (global) And parts (local).

Python There is a more scientific , The name used to describe the variable scope , Namespace (namespace).

Any variable assigned to a function , By default, they are assigned to local namespaces .
Local namespaces are created when a function is called , The function parameters will immediately fill in the namespace .

  • have access to global Keyword to declare a parameter in a function as a global variable .
  • However, frequent use is not recommended global keyword , Because global variables are generally used to store some states of the system .

1.2 Return multiple values

  • This function is better than Java、C++ It's too convenient . It's important to note that , When the function is called , The returned value must correspond to the received value one by one .
python
def f():
a = 5
b = 6
c = 7
return a, b, c
a, b, c = f()
  • in application , More commonly used is , Function returns only one object , It's just a tuple . Then split the tuple into each result variable .
def f():
a = 5
b = 6
c = 7
return {
'a' : a, 'b' : b, 'c' : c}
return_value = f()

1.3 Functions are also objects

  • For a complex string , Clean the data .
  • You need built-in string methods and regular expressions ——re modular .
In [171]: states = [' Alabama ', 'Georgia!', 'Georgia', 'georgia', 'FlOrIda', 'south carolina##', 'West virginia?']
import re
def clean_strings(strings):
result = []
for value in strings:
value = value.strip()
value = re.sub('[!#?]', '', value)
value = value.title()
result.append(value)
return result

(1)strip() Method

strip() Method is used to remove the characters specified at the beginning and end of a string ( The default is space or newline ) Or character sequence .
Return value : Modified character sequence .

Be careful : This method can only delete the characters at the beginning or the end , Middle part characters cannot be deleted .


(2)sub() Method
sub() Method is used to query and replace ,sub() The format of the method is :
re.sub(pattern, repl, string, count=0, flags=0)

pattern: Represents the pattern string in regular ;
repl: Represents the string to replace ( Match to pattern Replace with repl), It can also be a function ;
string: Means to be processed ( Search and replace ) Original string of ;
count: Optional parameters , Indicates the maximum number of times to replace , And it has to be a nonnegative integer , This parameter defaults to 0, That is, all matches will replace ;
flags: Optional parameters , Represents the matching pattern used at compile time ( If case is ignored 、 Multiline mode, etc ), Digital form , The default is 0.

(3)title() Method

title() Function of method : Converts the first letter of all words in a string to uppercase , All other letters are converted to lowercase .

【 Particular attention 】 If you encounter punctuation in a string 、 Space 、 Numbers and other non alphabetic elements , Then the first letter after the non alphabetic element is converted to uppercase , Other letters are converted to lowercase .

2 Some important functions

2.1 map() function

map yes python Built in functions for , The specified sequence will be mapped according to the provided function .

map() The format of the function is :

map(function, iterable,...)

The first parameter accepts a function name . The latter parameter accepts one or more iteratable sequences , What is returned is a collection .
Put the functions on list On every element in , Get a new one list And back to . Be careful :map The function does not change the original list, Instead, it returns a new list.

  • for instance :
del square(x):
return x ** 2
map(square,[1,2,3,4,5])
# give the result as follows :
[1,4,9,16,25]
  • When not introduced function when ,map() Is equivalent to zip(), Merge elements in the same position of multiple lists into a tuple :
map(None,[2,4,6],[3,2,1])
# give the result as follows 
[(2,3),(4,2),(6,1)]

2.2 Anonymous functions (lambda)

Python Supports an anonymous function , This function consists of only a single statement , The result of this statement is the return value .

adopt lambda Keyword definition , representative “ What is being declared is an anonymous function ”.

def short_function(x):
return x * 2
equiv_anon = lambda x: x * 2
  • Let's take a simple example :
def apply_to_list(some_list, f):
return [f(x) for x in some_list]
ints = [4, 0, 1, 5, 6]
apply_to_list(ints, lambda x: x * 2)

amount to :[x *2 for x in ints]

  • Another example :
def func(x,y):
return x+y
# It's equivalent to the following lambda
lambda x,y: x+y
  • Suppose you have a set of strings , You want to sort each string according to the number of different letters :
In [177]: strings = ['foo', 'card', 'bar', 'aaaa', 'abab']
In [178]: strings.sort(key=lambda x: len(set(list(x))))
In [179]: strings
Out[179]: ['aaaa', 'foo', 'abab', 'bar', 'card']

2.3 list() function

  1. list list() Method is used for Will iterate over objects ( character string 、 list 、 Yuan Zu 、 Dictionaries ) Convert to list .
T = (123, 'Google', 'Runoob', 'Taobao')
L1 = list(T)
print (" List elements : ", L1)
S="Hello World"
L2=list(S)
print (" List elements : ", L2)
###############################################
List elements : [123, 'Google', 'Runoob', 'Taobao']
List elements : ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

2.4 set() function

set() Function to create an unordered collection of non repeating elements .

Relationship testing is possible , Delete duplicate data , You can also compute the intersection 、 Difference set 、 And set etc. , Returns a new collection object

2.5 sort() Method

sort(*, key=None, reverse=False)
  1. Sorting is in place 、 The stability of the . Is the modified list itself , And it can maintain two positions of equal speaking speed .
  2. key Use of functions : Apply it to each list item , And sort the list in ascending or descending order according to their function values .
  3. reverse Set the reverse flag , Set to sort in ascending and descending order .

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