• 主页
  • 相册
  • 随笔
  • 目录
  • 存档
Total 244
Search AboutMe

  • 主页
  • 相册
  • 随笔
  • 目录
  • 存档

python小知识-1

2020-06-13

1. set().update方法

合并两个集合,重复元素只会出现一次

2. map

map(function, iterable, ...)

  • 返回值
    • Python 2.x 返回列表。
    • Python 3.x 返回迭代器。

两者区别见入门文章

3. sorted()

sorted(iterable, cmp=None, key=None, reverse=False)

  • 返回值
    • 返回重新排序的列表

sort 与 sorted 区别:

  • sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
  • list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。

4. help

help([object])

1
2
3
4
5
6
7
8
9
10
11
12
13
>>>help('sys')             # 查看 sys 模块的帮助
……显示帮助信息……

>>>help('str') # 查看 str 数据类型的帮助
……显示帮助信息……

>>>a = [1,2,3]
>>>help(a) # 查看列表 list 帮助信息
……显示帮助信息……

>>>help(a.append) # 显示list的append方法的帮助
……显示帮助信息……

5. set

集合(set)是一个无序的不重复元素序列。

可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典

python中集合set为什么会自动排序?

  • 元素排序依赖于hash算法等set具体实现细节。使用应依据官方文档,使用者不应认为set作为一种hash的应用是有序的,Python不保证其有序性。的确依据文档,在3.5还是3.6忘了,对dict的内部算法进行了修改。该算法结果将是有序的。但直到官方文档之后做出修改认定该有序性之前,你都不应该依赖它的有序性实现任何逻辑,因为下一版本它会说改就改成无序的实现。类似其他语言的”依赖编译器的trick”吧。这里是解释器。

知乎:尘浩

1
>>> i={[1],}                                                                                                            Traceback (most recent call last):                                                                                        File "<stdin>", line 1, in <module>                                                                                   TypeError: unhashable type: 'list

5.1. set.add() 与set.update()的区别

1
2
3
4
5
myset1 = set()
myset1.add('hello')
#{'hello'}
myset1.update('world')
#{'d', 'hello', 'l', 'o', 'r', 'w'}

6. hashable

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set
member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no
mutable containers (such as lists or dictionaries) are. Objects which
are instances of user-defined classes are hashable by default; they all
compare unequal, and their hash value is their id().

如果一个对象的哈希值在它的生命周期中从未改变(它需要一个__hash__()方法),并且可以与其他对象进行比较(它需要一个__eq__()或__cmp__()方法),那么这个对象就是可哈希的。Hashable 对象比较相等的对象必须有相同的哈希值.Hashability 使得一个对象可以作为字典键和集合成员使用,因为这些数据结构在内部使用哈希值.所有 Python 的不可变的内置对象都是可哈希的,而没有可变的容器 (如 list 或字典) 是可哈希的。作为用户定义类实例的对象默认是可哈希的;它们都比较不等,它们的哈希值是它们的id()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
>>> hash('Python')
1687380313081734297
>>>
>>> hash([1, 2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash({1, 2})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> hash({1 : 2})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>>
>>> hash(frozenset({1, 2}))
-1834016341293975159
>>> hash((1, 2))
3713081631934410656

6.1. frozenset()

class frozenset([iterable])

  • 返回新的 frozenset 对象,如果不提供任何参数,默认会生成空集合

为什么需要冻结的集合(即不可变的集合)呢?因为在集合的关系中,有集合的中的元素是另一个集合的情况,但是普通集合(set)本身是可变的,那么它的实例就不能放在另一个集合中(set中的元素必须是不可变类型)。

所以,frozenset提供了不可变的集合的功能,当集合不可变时,它就满足了作为集合中的元素的要求,就可以放在另一个集合中了

7. 正负无穷大

python中可以用如下方式表示正负无穷:

float("inf"), float("-inf")

利用 inf 做简单加、乘算术运算仍会得到 inf

1
2
3
1 + float('inf')
inf >>> 2 * float('inf')
inf

但是利用 inf 乘以0会得到 not-a-number(NaN):

1
2
0 * float("inf")
nan

除了inf外的其他数除以inf,会得到0

1
2
3
889 / float('inf') 0.0
float('inf')/float('inf')
nan

8. bisect

这个模块对有序列表提供了支持,使得他们可以在插入新数据仍然保持有序。对于长列表,如果其包含元素的比较操作十分昂贵的话,这可以是对更常见方法的改进。这个模块叫做 bisect 因为其使用了基本的二分(bisection)算法

bisect.bisect_left(a, x, lo=0, hi=len(a))

  • 在 a 中找到 x 合适的插入点以维持有序。参数 lo 和 hi 可以被用于确定需要考虑的子集;默认情况下整个列表都会被使用。如果 x 已经在 a 里存在,那么插入点会在已存在元素之前(也就是左边)。如果 a 是列表(list)的话,返回值是可以被放在 list.insert() 的第一个参数的

8.1. 搜索有序列表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError

def find_lt(a, x):
'Find rightmost value less than x'
i = bisect_left(a, x)
if i:
return a[i-1]
raise ValueError

def find_le(a, x):
'Find rightmost value less than or equal to x'
i = bisect_right(a, x)
if i:
return a[i-1]
raise ValueError

def find_gt(a, x):
'Find leftmost value greater than x'
i = bisect_right(a, x)
if i != len(a):
return a[i]
raise ValueError

def find_ge(a, x):
'Find leftmost item greater than or equal to x'
i = bisect_left(a, x)
if i != len(a):
return a[i]
raise ValueError

9. re.search()

search()函数会在整个字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None

1
2
3
ss=re.compile(r'((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(1\d\d|2[0-4]\d|25[0-5]|[1-9]\d|\d)')

print(ss.search('asdada172.26.133.84').group())

10. 读数据

1
2
a=sys.stdin.readline().strip(')
list(map(int,a.split()))

11. ValueError: invalid literal for int() with base 10: ‘u’

input函数返bai回的是string类型,即字符串

int函数将字符串形式的du数值转换为整数时,字zhi符串中dao只能包含数字

所以正确的方法应该是现将字符串转换成后float,再将float转换成int

a=int(float(input()))

12. 四舍五入

1
2
>>> round(2.3)
2

13. os.popen()

os.popen()方法用于从一个命令打开一个管道。

1
2
3
4
5
6
7
8
9
import os, sys

# 使用 mkdir 命令
a = 'mkdir nwdir'

b = os.popen(a,'r',1)

print b
# open file 'mkdir nwdir', mode 'r' at 0x81614d0

14. open()

  • open()创建新的文件对象,os.open()创建操作系统级文件描述符,os.fdopen()从文件描述符中创建一个文件对象。
  • 文件描述符是用于处理由操作系统内核直接提供的文件的低级功能。文件描述符是一个小整数,用于标识内核为每个进程保留的打开文件的表中的打开文件。许多系统调用接受文件描述符,但它们不方便使用,通常需要固定宽度的缓冲区,某些条件下的多次重试以及手动错误处理。
  • 文件对象是包含文件描述符的Python类,使文件更方便,容易出错。它们提供了例如错误处理,缓冲,逐行读取,字符集转换,并在收集垃圾时关闭
  • 在python中os.open和os.fdopen之间有什么区别? - 程序园
  • Program Language
  • Python
  • Basic
Javascript-Overview
高性能mysql-1
  1. 1. 1. set().update方法
  2. 2. 2. map
  3. 3. 3. sorted()
  4. 4. 4. help
  5. 5. 5. set
    1. 5.1. 5.1. set.add() 与set.update()的区别
  6. 6. 6. hashable
    1. 6.1. 6.1. frozenset()
  7. 7. 7. 正负无穷大
  8. 8. 8. bisect
    1. 8.1. 8.1. 搜索有序列表
  9. 9. 9. re.search()
  10. 10. 10. 读数据
  11. 11. 11. ValueError: invalid literal for int() with base 10: ‘u’
  12. 12. 12. 四舍五入
  13. 13. 13. os.popen()
  14. 14. 14. open()
© 2024 何决云 载入天数...