0
点赞
收藏
分享

微信扫一扫

Python小知识

新鲜小饼干 2022-03-13 阅读 125

变量作用域

只有模块(module),类(class)和函数(def、lambda)才会引入新的作用域,if/elif/else/、try/except、for/while 等语句则不会引入新的作用域,即外部可以访问在这些语句内定义的变量。

x = 3
for i in range(5):
    x = 1

print(x)    # 1
x = 7
def f():
    global x
    y = x
    print(y)    # 7
    x = 2

f()

Operator

//

print(5//0.5)   # 10.0

valid ways to declar complex numbers

z = 5 * 1j
print(type(z))	# <class 'complex'>
a = 1 + 5j
print(type(a))	# <class 'complex'>
b = complex(3)
print(type(b))	# <class 'complex'>

2 == 2.0 is True

is关键字

The is keyword is used to test if two variables refer to the same object.

The test returns True if the two objects are the same object.

The test returns False if they are not the same object, even if the two objects are 100% equal.

Use the == operator to test if two variables are equal.

x = ["apple", "banana", "cherry"]

y = ["apple", "banana", "cherry"]

print(x is y)	# False
print(x == y)	# True
y = x
print(x is y)	# True
print(x == y)	# True

Lambda

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

lambda arguments : expression
A = {1,2,3,5,3,2,1}
print(type(A))  # <class 'set'>
print(A)    # {1, 2, 3, 5}
print(list(filter(lambda x : x % 2 == 0, A)))   # [2]
print(sum(list(filter(lambda x: x%2 == 0, A)))) # 2

Built in Functions

zip() Function

The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.

filter() Function

The filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.

ages = [5, 12, 18, 18, 24, 32]

def myFunc(x):
  if x < 18:
    return False
  else:
    return True

adults = filter(myFunc, ages)
print(list(adults))

int() Function

print(int('3')) # 3
print(type(int('3')))   # <class 'int'>
print(int(0.5))	# 0
print(int('4.0'))   # ValueError: invalid literal for int() with base 10: '4.0'

print() Function

print(object(s), sep=separator, end=end, file=file, flush=flush)
ParameterDescription
object(s)Any object, and as many as you like. Will be converted to string before printed
sep=‘separator’Optional. Specify how to separate the objects, if there is more than one. Default is ’ ’
end=‘end’Optional. Specify what to print at the end. Default is ‘\n’ (line feed)
fileOptional. An object with a write method. Default is sys.stdout
flushOptional. A Boolean, specifying if the output is flushed (True) or buffered (False). Default is False
a = [0]
print(a)    # [0]
b = [a]
print(b)    # [[0]]
c = b[0]
print(c)    # [0]
print(a, b, c)  # [0] [[0]] [0]

round() Function

print(round(1234.5))    # 1234
print(round(1234.500001))   # 1235

print(round(1234.125,2))    # 1234.12
print(round(1234.1250001,2))    #1234.13

print(round(1234.1499999,1))    # 1234.1
print(round(1234.15,1)) # 1234.2

print(round(1234.5,0))  # 1234.0
print(round(1234.500001,0)) # 1235.0

print(round(1234.9999,-1))  # 1230.0
print(round(1235,-1))   # 1240
print(round(1235.0,-1)) # 1240.0

print(round(1250,-2))   # 1200
print(round(1250.0,-2)) # 1200.0
print(round(1250.00001,-2)) # 1300.0

Tuple

Tuples are used to store multiple items in a single variable.

Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Tuple items are ordered, unchangeable, and allow duplicate values.

’tuple’ object has no attribute 'sort’

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.

Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.

Since tuples are indexed, they can have items with the same value:

To determine how many items a tuple has, use the len() function:

To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple.

thistuple = ("apple",)
print(type(thistuple))	# <class 'tuple'>

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))	# <class 'str'>

Tuple items can be of any data type

A tuple can contain different data types

From Python’s perspective, tuples are defined as objects with the data type ‘tuple’

It is also possible to use the tuple() constructor to make a tuple.

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets, tuple expected at most 1 argument
print(thistuple)
t1 = (1, 2, 3)
t2 = ('a', 'b', 'c', "d")

x = zip(t1, t2)
print(x)
print(tuple(x))	# ((1, 'a'), (2, 'b'), (3, 'c'))
print(x)
print(tuple(x))	# ()
print(x)
t1 = (1, 2, 3)
t2 = ('a', 'b', 'c', "d")


print(tuple(zip(t1, t2)))	# ((1, 'a'), (2, 'b'), (3, 'c'))
print(tuple(zip(t1, t2))[1][0])	# 2

As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

itertools

import itertools
original_list = [[2, 4, 3], [1, 5, 6]]
new_list = list(itertools.chain(*original_list))
print(new_list)	# [2, 4, 3, 1, 5, 6]
s = 'abc'
i = iter(s)
next(i)
print(next(i))	# b

unhashable type: ‘list’

TypeError: unhashable type: ‘list’ usually means that you are trying to use a list as an hash argument. This means that when you try to hash an unhashable object it will result an error. For ex. when you use a list as a key in the dictionary , this cannot be done because lists can’t be hashed. The standard way to solve this issue is to cast a list to a tuple.

my_dict = {'name': 'John', [1,2,3]:'values'}
print(my_dict)

This error shows that the my_dict key [1,2,3] is List and List is not a hashable type in Python . Dictionary keys must be immutable types and list is a mutable(可变的) type.

Fix: Cast list to a tuple
You’ll have to change your list into tuples if you want to put them as keys in your dictionary.

my_dict = {'name': 'John', tuple([1,2,3]):'values'}
print(my_dict)

The hash() is a built-in python method, used to return a unique number. This can be applied to any user-defined object which won’t get changed once initialized. This property is used mainly in dictionary keys.

Examples of hashable objects:

Examples of Unhashable objects:

Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking or indexing. Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

Hashing is a concept in computer science that is used to create high-performance, pseudo-random access data structures where a large amount of data is to be stored and accessed quickly. Immutable objects, or objects that can’t be altered, are hashable and they have a single unique value that will never change. A hashing function is a function that takes an object, say a string such as “Java” and returns a fixed-size code, assuming the return value is an integer.

time

to add a delay of 1 minute

import time
time.sleep(60)

Math Methods

math.sqrt() Method

return a float

String

Python String find() Method

The find() method finds the first occurrence of the specified value.

The find() method returns -1 if the value is not found.

The find() method is almost the same as the index() method, the only difference is that the index() method raises an exception if the value is not found.

txt = "Hello, welcome to my world."

x = txt.find("welcome")

print(x)	# 7

Python String format() Method

The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even empty placeholders {}.

#named indexes:
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
#numbered indexes:
txt2 = "My name is {0}, I'm {1}".format("John",36)
#empty placeholders:
txt3 = "My name is {}, I'm {}".format("John",36)

print(txt1)
print(txt2)
print(txt3)
vals = [2,4,7]
new = "{1}{2}{1}".format(2,7,4)
print(new)	# 747
print(1.0/3)    # 0.3333333333333333(16个3)
print('{:.2}'.format(0.33333))  # 0.33
print('{:.3}'.format(0.33333))  # 0.333
print('{:.2}'.format(1.0/3))    # 0.33
print('{0:.2}'.format(1.0/3))   # 0.33

Python String split() Method

string.split(separator, maxsplit)

The split() method splits a string into a list.

You can specify the separator, default separator is any whitespace.

Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

txt = "123"
print(type(txt[0]))	# <class 'str'>
print(txt[0])	# 1
x = txt.split()
y = txt.split('1')

print(x)	# ['123']
print(y)	# ['', '23']
txt = "apple#banana#cherry#orange"

# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.split("#", 1)

print(x)	# ['apple', 'banana#cherry#orange']

Python String zfill() Method

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length.

If the value of the len parameter is less than the length of the string, no filling is done.

a = "hello"
b = "welcome to the jungle"
c = "10.000"

print(a.zfill(10))	# 00000hello
print(b.zfill(10))	# welcome to the jungle
print(c.zfill(10))	# 000010.000

remove() is a mutable set member function.

Python allows us to implement more than one decorator to a function.

if you rename functions of an imported module using the as keyword, you can’t use the original name of the function

random

Python Random choice() Method

The choice() method returns a randomly selected element from the specified sequence.

The sequence can be a string, a range, a list, a tuple or any other kind of sequence.

Lists, tuples, and strings have been called sequences, because their items occur in order. The dictionary is the first compound type that we’ve seen that is not a sequence, so we can’t index or slice a dictionary.

map

The map() function executes a specified function for each item in an iterable. The item is sent to the function as a parameter.

The sum() function returns a number, the sum of all items in an iterable.

x = [3,4],(4,7),{7,11,7,11}
s = map(sum, x)
print(sum([3,4]))	# 7
print(sum((4,7)))	# 11
print(sum({7,11,7,11}))	# 18 Set items are unordered, unchangeable, and do not allow duplicate values.
# print(list(s))
print(sum(s))	# 36

Set items are unordered, unchangeable, and do not allow duplicate values.

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)	# {'banana', 'apple', 'cherry'}

List

Python List insert() Method

The insert() method inserts the specified value at the specified position.

list.insert(pos, elmnt)
ParameterDescription
posRequired. A number specifying in which position to insert the value
elmntRequired. An element of any type (string, number, object etc.)

Python List reverse() Method

fruits = ['apple', 'banana', 'cherry']

print(fruits.reverse())	# None

print(fruits)	# ['cherry', 'banana', 'apple']
a = [8,0,4,6]
print(a[::-1])  # [6, 4, 0, 8]
print(type(a[::-1]))    # <class 'list'>
if a.reverse() == a[::-1]:
    print(True)
else:
    print(False)    # False

reverse() method returns None because it reverses the list in place. It doesn’t return a new reversed list.

Python List append() Method

The append() method appends an element to the end of the list.

def build_list(element, to=[]):
    to.append(element)
    return to
my_list = build_list(2)
print(my_list)  # [2]
my_other_list = build_list(5)
print(my_other_list)    # [2, 5]

Python List extend() Method

The extend() method adds the specified list elements (or any iterable) to the end of the current list.

A = [1,2]
B = [3,4]
C = A.extend(B)
print(C)    # None
print(A)    # [1, 2, 3, 4]
print(B)    # [3, 4]

Dictionary

Python Dictionary update() Method

The update() method inserts the specified items to the dictionary.

The specified items can be a dictionary, or an iterable object with key value pairs.

prefs = {"fruit":"apple","car":"Tesla"}
prefs2 = {"fruit":"orange"}
prefs.update(prefs2)
print(prefs)    # {'fruit': 'orange', 'car': 'Tesla'}

Slicing Strings

Use negative indexes to start the slice from the end of the string
Example
Get the characters:

From: “o” in “World!” (position -5)

To, but not included: “d” in “World!” (position -2):

b = "Hello, World!"
print(b[-5:-2])	# orl

在这里插入图片描述

a = [8,0,4]
print(a[2:5])   # [4]
print(a)    # [8, 0, 4]

if else

x = 6
y = 2 if x > 6 else 3
print(y)	# 3

and or

a = 1 == 1 or 1 != 1
print(a)    # True
b = a == 1 and 2 != 2.0
print(b)    # False
print(True == 1)    # True

OOP(TO DO)

class MyClass():
    n = 0
    def __init__(self):
        MyClass.n += 1
    def __del__(self):
        MyClass.n -= 1
a = MyClass()
print(a.n)  # 1
b = MyClass()
print(b.n)  # 2
a = MyClass()
print(a.n)  # 2
class Parent(object):
    x = 1
class Child1(Parent):
    pass
class Child2(Parent):
    pass
Child1.x = 2
Parent.x = 3
print(Parent.x) # 3
print(Child1.x) # 2
print(Child2.x) # 3
class Tower:
    def __init__(self, x = 10):
        self.hp = x
A = Tower()
B = Tower(9)
C = Tower(2)
print(A.hp + C.hp - B.hp)   # 3

NumPy

NumPy is used to work with arrays. The array object in NumPy is called ndarray.

We can create a NumPy ndarray object by using the array() function.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))
import numpy as np
arr = np.array([[2,0],[2,0]])
print(arr)
print(arr.mean())   # 1.0
list = [[2,0],[2,0]]
print(list)

numpy.ones

numpy.ones(shape, dtype=None, order='C', *, like=None)
import numpy as np
ar = np.ones((3,2)) # 3行2列
print(ar)
print(type(ar))
print(ar.ndim)  # 2

Return a new array of given shape and type, filled with ones.

numpy.ndarray.ndim

Number of array dimensions.

RegEx Meta Characters

metacharacter ‘.’ matches any character, other than a new line.

import re

txt = "hello planet"

#Search for a sequence that starts with "he", followed by two (any) characters, and an "o":

x = re.findall("he..o", txt)
print(x)	# ['hello']

global

n = 0
def func(x = 0):
    global n    # 没有这行会报错local variable 'n' referenced before assignment
    n = n + 1
    return n
print(func(func()))	# 2

Try Except

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

print(0**0)
try:
    print(0**0, end="")
except e:
    print(0, end="")
finally:
    print(2, end="")

output:

1
12

参考资料
http://net-informations.com/python/iq/unhashable.htm

举报

相关推荐

0 条评论