python 用法备忘

 

1.

>>> odds = [1, 3, 5, 7, 9]
>>> [x+1 for x in odds]
[2, 4, 6, 8, 10]

2.

>>> [x for x in odds if 25 % x == 0]
[1, 5]

 3

>>> digits = [1, 8, 2, 8]
>>>[2, 7] + digits * 2
[2, 7, 1, 8, 2, 8, 1, 8, 2, 8]

4.

pairs = [[1, 2], [2, 2], [2, 3], [4, 4]]
>>> for x, y in pairs:
        if x == y:
            same_count = same_count + 1
>>> same_count
2

5. evaluating an expression for each element in a sequence can be expressed by applying a function to each element.

>>> def apply_to_all(map_fn, s):
        return [map_fn(x) for x in s]

6.Selecting only elements for which some expression is true can be expressed by applying a function to each element.

>>> def keep_if(filter_fn, s):
        return [x for x in s if filter_fn(x)]

7.many forms of aggregation can be expressed as repeatedly applying a two-argument function to the reduced value so far and each element in turn.

>>> def reduce(reduce_fn, s, initial):
        reduced = initial
        for x in s:
            reduced = reduce_fn(reduced, x)
        return reduced

For example, reduce can be used to multiply together all elements of a sequence. Using mul as the reduce_fn and 1 as the initial value, reduce can be used to multiply together a sequence of numbers.

 

>>> reduce(mul, [2, 4, 8], 1)
64

 

8.print tree

def print_tree(t,indent=0):
    if is_leaf(t):
        print(' '*indent,label(t))
    else:
        print(' '*indent,label(t))
        for b in branches(t):
            print_tree(b,indent+1)
    

9. list sum

>>>sum([['a'],['b']],['c']
['c', 'a', 'b']

eg:

 1 def preorder(t):
 2     """Return a list of the entries in this tree in the order that they
 3     would be visited by a preorder traversal (see problem description).
 4     >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
 5     >>> preorder(numbers)
 6     [1, 2, 3, 4, 5, 6, 7]
 7     >>> preorder(tree(2, [tree(4, [tree(6)])]))
 8     [2, 4, 6]
 9     """
10     "*** YOUR CODE HERE ***"
11     return [label(t)] + sum([preorder(b) for b in branches(t)],[])

 

 

10. tree square

def square_tree(t):
    if is_leaf(t):
        return tree(label(t)**2)
    lst=[]
    for b in branches(t):
        lst+=square_tree(b)
    return tree(label(t)**2,lst)

 11. 

>>>leaves=[6,5]
>>>tree(90,[tree(x) for x in leaves])
[90, [6], [5]]

 

12.

1  if is_leaf(t):
2         if label(t)==find_value:
3             return tree(replace_value)
4         else:
5             return tree(label(t))
6 
7 #return tree(replace_value if label(t)==find_value else label(t))

 13.将变量赋值为最大值或者最小值

min_value = float('-inf')
#赋值为负无穷

max_value=float('inf')
#赋值为正无穷

 14.enumerate 

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

 语法:
enumerate(sequence, [start=0])

example:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
>>> seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
...
0 one
1 two
2 three

 

15. max min with key

example 1:Get the largest item in a list

number = [3, 2, 8, 5, 10, 6]
largest_number = max(number);

print("The largest number is:", largest_number)
The largest number is: 10
 
example 2:the largest string in a list
ps:如果可迭代对象中的项是字符串,则返回最大的项(按字母顺序排序)。
languages = ["Python", "C Programming", "Java", "JavaScript"]
largest_string = max(languages);

print("The largest string is:", largest_string)
The largest string is: Python
 
example 3: max() in dictionaries

In the case of dictionaries, max() returns the largest key. Let's use the key parameter so that we can find the dictionary's key having the largest value. 

 1 square = {2: 4, -3: 9, -1: 1, -2: 4}
 2 
 3 # the largest key
 4 key1 = max(square)
 5 print("The largest key:", key1)    # 2
 6 
 7 # the key whose value is the largest
 8 key2 = max(square, key = lambda k: square[k])
 9 
10 print("The key with the largest value:", key2)    # -3
11 
12 # getting the largest value
13 print("The largest value:", square[key2])    # 9
The largest key: 2
The key with the largest value: -3
The largest value: 9

其实就是将列表的值代入key这个函数得到一个新的列表,再在这个新的列表中取最大值。

 16.dictinoary scope

number = 0
def incrementNumber():
    number += 1
number = {'num':0}
def incrementNumber():
    number['num'] += 1

the first code is not work,but the second is work

dictionaryVar = {'A':"original"}
stringVar = "original"
globalStringVar = "original"

def aFunction():
    global globalStringVar
    dictionaryVar['A']="changed"
    stringVar = "changed"
    globalStringVar="changed"
    return dictionaryVar, stringVar, globalStringVar

print ("Output of the function is:")
a = aFunction()
print ("Dictionary   : ")
print (a[0])
print ("String       : "+a[1])
print ("Global String: "+a[2])
print ("\nGlobal variables are now: ")
print ("Dictionary   : ",)
print (dictionaryVar)
print ("String       : "+stringVar)
print ("Global String: "+globalStringVar)
Output of the function is:
Dictionary   : 
{'A': 'changed'}
String       : changed
Global String: changed

Global variables are now: 
Dictionary   : 
{'A': 'changed'}
String       : original
Global String: changed

conclusion:

  • Global strings changed in a function are returned correctly, and not changed outside the scope of the function. (expected)
  • Global dictionaries changed in a function are returned correctly, but they are also changed outside the scope of the function. (not expected)
  • Global strings, declared as global (in the function), changed in a function are returned correctly, and are also changed outside the scope of the function. (expected)

 

17. memoization

def fibonacci(n, cache={}):
    if n in cache:
        return cache[n]
    if n < 2:
        return n
    result = fibonacci(n-1) + fibonacci(n-2)
    cache[n] = result
    return result

这个 cache 字典并不是全局变量,它是定义在函数参数列表中的一个默认参数。默认参数在 Python 中只会在函数定义时被计算一次,然后在函数的每次调用中都会使用同一个对象,因此在 fibonacci 函数的多次递归调用中,cache 字典都是同一个对象。

这个特性可以用来实现缓存的效果:在函数的多次调用中,都可以共享同一个缓存,避免重复计算。在这里,cache 字典就被用来缓存斐波那契数列的计算结果,以避免重复计算。

需要注意的是,如果使用可变对象作为默认参数,需要特别小心,因为默认参数只会在函数定义时被计算一次,而在函数的多次调用中,都会使用同一个对象。如果在函数内部修改了默认参数,那么这些修改会影响到后续的函数调用。因此,如果需要在函数内部修改默认参数,建议使用不可变对象作为默认参数,或者在函数内部创建新的可变对象来避免修改默认参数。

 

18. attributes and methods

Objects have attributes, which are named values that are part of the object. 

Objects also have methods, which are function-valued attributes.

In Python, attributes and methods are both used to define the behavior and properties of an object, but they serve different purposes.

An attribute is a variable that is bound to an object, and it stores some information about the object. It can be accessed using the dot notation (e.g., object.attribute), and it can be either a built-in data type or a user-defined class. Attributes can be either public or private, depending on how they are named. Public attributes are those that are accessible from outside the class, while private attributes are those that can only be accessed from within the class.

A method, on the other hand, is a function that is bound to an object. It defines the behavior of the object and allows the object to perform some action or computation. Methods are accessed using the same dot notation as attributes (e.g., object.method()), but they always have a set of parentheses after their name. Methods can also be either public or private, and they can take parameters and return values.

In summary, the main difference between attributes and methods in Python is that attributes store data about an object, while methods define the behavior of an object and allow it to perform some action or computation.

19. about list,什么时候改变会造成原list的改变,像c++ 的引用;什么时候是创造一个new list,不会对原list造成影响,就像是浅拷贝

chinese=['coin','string','myriad']
suits=chinese
>>>suits
['heart', 'diamond', 'spade', 'club']
nest=list(suits) #Bind "nest" to a second list with the same elements
nest[0]=suits     #create a nested list
suits.insert(2,'Joker') #Insert an element at index 2 ,shifting the rest
#>>>nest
#[['heart', 'diamond', 'Joker', 'spade', 'club'], 'diamond', 'spade', 'club']
 总结:
1. new_list=old_list
这就是浅拷贝,and new_list 是直接指向old_list, old_list 改变,new_list也会改变,时时刻刻相等。
2.new_list=list(old_list)
这就是深拷贝,在将old_list中的值赋值给new_list之后,二者就不会有任何关联。
 
20. identity and equal in list
>>> suits is nest[0]  #indentical
True
>>> suits is ['heart', 'diamond', 'spade', 'club']
False
>>> suits == ['heart', 'diamond', 'spade', 'club']  #equal
True

Because two lists may have the same contents but in fact be different lists, we require a means to test whether two objects are the same. Python includes two comparison operators, called is and is not, that test whether two expressions in fact evaluate to the identical object. Two objects are identical if they are equal in their current value, and any change to one will always be reflected in the other. Identity is a stronger condition than equality.

21.Tuples

tuples are immutable.

While it is not possible to change which elements are in a tuple, it is possible to change the value of a mutable element contained within a tuple.

nest=(10,20,[30,40])
print(nest)
nest[2].pop()
print(nest)
(10, 20, [30, 40])
(10, 20, [30])

 

22.nonlocal

Effect:

Effect: Future assignments to that name change its pre-existing binding in the first non-local frame of the current environment(enclosing scope,闭包),inwhich that name is bound.

focus:

1.names listed in a nonlocal statement must refer to pre-existing bindings in an enclousing scope 

2.Names listed in a nonlocal statement must not collide with pre-existing bindings in the local scopel

def make_withdraw(balance):
    def withdraw(amount):
        if amount >balance:  #error
            return 'Insufficient funds'
        balance=balance-amount  #assignment
        return balance
    return withdraw
wd=make_withdraw(20)
wd(5)

此时会发生错误,因为这里的balance没有定义,而且后面又有一个重新的assignment,就会让编译器认为这是在定义。所以造成错误。

但是如果没有这个assignment,就不会产生错误,编译器就会自动调用parent frame里面的balance。可是如果是这样,就不会更新balance,有什么解决的办法呢?

1 def make_withdraw(balance):
2     def withdraw(amount):
3         if amount >balance:  #error
4             return 'Insufficient funds'
5         new_balance=balance-amount
6         return new_balance
7     return withdraw
8 wd=make_withdraw(20)
9 wd(5)

将balance更换名称,改为new_balance.

3.

  • Nonlocal allows you to modify a binding in a parent frame, instead of just looking it up
  • Don't need a nonlocal statement to mutate a value
  • A variable declared nonlocal must:   
    • Not exist in the current frame
    • Exist in a parent frame (other than the global frame),

 

 

22. generators and yield 

1 r = range(3, 6)
2 ri = iter(r)
3 for i in ri:
4     print(i)
5 print("This is new test")
6 for i in ri:
7     print(i)

特殊的地方在于,第二次循环时不会打印出i,因为iterator已经推进结束,到达终点了。

def  a_then_b(a,b):
    for x in a:
        yield x
    for x in b:
        yield x

def new_a_then_b(a,b):
    yield from a
    yield from b

这两段程序是相同的效果。

如何返回多个generator

>>> nums_squared_lc = [num**2 for num in range(5)]
>>> nums_squared_gc = (num**2 for num in range(5))

>>> nums_squared_lc
[0, 1, 4, 9, 16]
>>> nums_squared_gc
<generator object <genexpr> at 0x107fbbc78>

 

23.

 Using getattr, we can look up an attribute using a string, just as we did with a dispatch dictionary.

>>> getattr(spock_account, 'balance')
10

 

We can also test whether an object has a named attribute with hasattr.

>>> hasattr(spock_account, 'deposit')
True

 

24.Class attribute and instance attribute 

如果直接对类名进行更改attribute,就会更改所有的 instantiations.而如果只是通过引用instantiation来更改attribute,就只会更改this single instantiation,需要注意的是,此时再更改class attribute,this single instantiation 's attribute not change

>>> spock_account = Account('Spock')
>>> kirk_account = Account('Kirk')
>>> spock_account.interest
0.02
>>> kirk_account.interest
0.02
>>> Account.interest = 0.04
>>> spock_account.interest
0.04
>>> kirk_account.interest
0.04
>>> kirk_account.interest = 0.08
>>> kirk_account.interest
0.08
>>> spock_account.interest
0.04

 

25.special mathods

In Python, certain special names are invoked by the Python interpreter in special circumstances.

For instance, the __init__ method of a class is automatically invoked whenever an object is constructed.

The __str__ method is invoked automatically when printing, and __repr__ is invoked in an interactive session to display values.

更多详细用法

 
 
26.在 Python 中,子类是父类的一种,因此 isinstance(子类的实例化, 父类) 为真。
 
27.__str__ __repr__

__str____repr__都是用于返回对象的字符串表示形式的特殊方法,但它们的使用场景和返回结果是不同的。

__str__方法用于返回一个对象的用户友好的字符串表示形式,通常用于打印或显示给终端用户。而__repr__方法用于返回一个对象的开发者友好的字符串表示形式,通常用于调试或开发过程中的输出。

下面是一些总结__str____repr__之间区别的关键点:

  • __str__返回一个对象的可读字符串表示形式,而__repr__返回一个对象的开发者友好的字符串表示形式。
  • __str__应该返回一个简短、易于阅读的字符串,而__repr__通常返回一个详细的、准确的表示该对象的字符串。
  • __str__的返回值应该是一种人类可读的格式,而__repr__返回的是一种Python表达式格式,可用于重建该对象。
  • 当调用str()函数时,Python会尝试调用__str__方法,而如果__str__方法未定义,则会调用__repr__方法。
  • 当你使用交互式Python解释器或调试器等工具来检查对象时,Python会自动调用__repr__方法,因为该方法的结果是一种完整的、准确的表示该对象的字符串。

总之,__str____repr__是用于返回对象字符串表示形式的特殊方法,它们的使用场景和返回结果是不同的。__str__通常用于向用户显示对象的信息,而__repr__通常用于开发和调试过程中的输出。

 

当你使用print()函数来打印一个对象时,Python会首先尝试调用该对象的__str__方法来获取其用户友好的字符串表示形式,如果该方法未定义,则会调用__repr__方法来获取开发者友好的字符串表示形式。

所以,如果一个对象同时定义了__str____repr__方法,那么在使用print()函数时,通常会调用__str__方法返回其用户友好的字符串表示形式。

如果一个对象只定义了__repr__方法而没有定义__str__方法,那么在使用print()函数时,将会调用其__repr__方法返回其开发者友好的字符串表示形式。如果一个对象既没有定义__str__方法,也没有定义__repr__方法,则print()函数将使用默认的对象字符串表示形式来打印该对象。

 
 
27.
string  = input()
str_map = {}
for ele in string :
    if ele.isalpha():
        str_map[ele.lower()] = str_map.get(ele.lower(), 0) + 1
str = [(letter, num) for letter, num in str_map.items()]
str_sorted = sorted(str, key = lambda x : x[1], reverse = True)
for i in range(5):
    print("{0} {1}".format(str_sorted[i][0], str_sorted[i][1]))

如何对字典进行排序:可以现将 key , value 变为一个元组,然后再进行排序。

posted @ 2023-03-21 19:57  哎呦_不想学习哟~  阅读(39)  评论(0)    收藏  举报