加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

【Python】收集的高级函数、功能

发布时间:2020-05-27 04:45:20 所属栏目:Python 来源:互联网
导读:说明:本文更新顺序是从下到上,最新的函数更新在开头。Python日志实时写入
<tr><td style="border-color:#cccccc;vertical-align:baseline;">

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

说明:本文更新顺序是从下到上,最新的函数更新在开头。

Python日志实时写入

<pre class="has">
open 函数中有一个bufferin的参数,默认是-1,如果设置为0是,就是无缓冲模式。
但是用二进制模式打开这个文件,并且把要写入的信息转换byte -like如下。

with open("test.txt",'wb',buffering=0) as f:

wb是写模式加二进制模式

f.write(b"hello!")在字符串前加b,转换成二进制

如果没用二进制打开文件会提示ValueEorror:

没把字符串转成二进制会提示:TypeError: a bytes-like object is required,not ‘str’

测试:

<pre class="has">
class Logger(object):
def init(self,log_path="default.log"):
self.terminal = sys.stdout

self.log = open(log_path,"w+")

    self.log = open(log_path,"wb",buffering=0)

def print(self,message):
    self.terminal.write(message + "n")
    self.log.write(message.encode('utf-8') + b"n")

def print_time(self,text=""):
    message = time.strftime('[ %Y-%m-%d %H:%M ]',time.localtime(time.time())) + text
    self.print(message)

def flush(self):
    self.terminal.flush()
    self.log.flush()

def close(self):
    self.log.close()

报错:TypeError: can't concat str to bytes

这是因为:

(1)log.write需要写入bytes对象,encode返回的是bytes型的数据,不可以和str相加,将‘n’前加b

(2)terminal.write函数参数需要为str类型,转化为str

<pre class="has">
a=np.arange(10)
a
array([0,1,2,3,4,5,6,7,8,9])
a[0]=11
a
array([11,9])
np.argsort(a)
array([1,9,0],dtype=int64)

首先这里p_arr为一个numpy的array,p_为一个元素

<pre class="has">
p_arr = np.concatenate((parr,[p])) # 先将p_变成list形式进行拼接,注意输入为一个tuple
p_arr = np.append(parr,p) #直接向parr里添加p

注意一定不要忘记用赋值覆盖原p_arr不然不会变

但是,仍然建议用list子代append。因为numpy的append默认添加的值全转化为float64了。

shutil.copy(sourceDir,targetDir)

os.path.join():路径拼接

<pre class="has">
import networkx as nx

抽取txt中的数据

def read_txt(data):
g = nx.read_edgelist("data",create_using=nx.DiGraph())
print(g.edges())

抽取gml中的数据

networkx可以直接通过函数从gml文件中读出数据

def read_gml(data):
H=nx.read_gml(data)
print(H.edges())

read_txt('D:Artifical平均度4SF2-4.txt')
print('---------------gml------------------')
read_gml('D:文档论文代码社区发现数据dataadjnounadjnoun.gml')


原文:https://blog.csdn.net/qq_38266635/article/details/81743336

<pre class="has">
<code class="language-html">while len(list(nx.dfs_edges(G)))!=G.number_of_nodes()-1:
G = RG(100,e)
print("not connected!")

def get_adj_matrix(G):
return nx.adjacency_matrix(G).todense()

todense()与toarray()

todense()返回一个矩阵,toarray()返回一个numpy数组。

np.random.choice

1、以p的概率,在a中取size个数,p值越大越可能被取到;2、当replace=True时,取值可重复

<pre class="has">
import numpy as np
a1=np.array([3,2.6,41.2,5.7])
a2 = np.random.choice(a=a1,size=3,replace=False,p=[0.2,0.1,0.3,0.4,0.0])
print(a2)
输出: array([41.2,5.,2.6])

注意sample是属于random模块,而不是nump.random模块,二者不一样。

注意n必须是整数,返回一个列表。

a = [[1,2],[3,4],[5,6]]

1.sum(map(sum,a)) #first,map(func,a) 函数是对a中的每一个元素进行sum操作

解释一下map函数, map(fund,a) equals [func(i) for i in a] and return a list

2.sum(sum(i) for i in a) #second one

3.sum(sum(a[i]) for i in range(len(a))) #third one

4.reduce(lambda x,y:x+y,reduce(lambda x,a))
---------------------
作者:jinmingz
来源:CSDN
原文:https://blog.csdn.net/zjm750617105/article/details/51173032
版权声明:本文为博主原创文章,转载请附上博文链接!

  • reshape:有返回值,所谓有返回值,即不对原始多维数组进行修改;
  • resize:无返回值,所谓有返回值,即会对原始多维数组进行修改;
  • 但是,numpy.resize(a,size)不会对原数组进行修改。
>> X = np.random.randn(2,3)
>> X
array([[ 1.23077478,-0.70550605,-0.37017735],[-0.61543319,1.1188644,-1.05797142]])

X.reshape((3,2))
array([[ 1.23077478,-0.70550605],[-0.37017735,-0.61543319],[ 1.1188644,-1.05797142]])

X
array([[ 1.23077478,-1.05797142]])

X.resize((3,2))
X
array([[ 1.23077478,-1.05797142]])

来自:https://blog.csdn.net/lanchunhui/article/details/51258503?utm_source=copy

(1)通过reshape生成的新数组和原始数组公用一个内存,也就是说,假如更改一个数组的元素,另一个数组也将发生改变。

(2)reshape只能作用于能规整划分的数组。

<pre class="has">
<code class="language-python">>>> z = np.array([[1,8],[9,10,11,12],[13,14,15,16]])

print(z)
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
print(z.shape)
(4,4)
print(z.reshape(-1))
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
print(z.reshape(-1,1)) #我们不知道z的shape属性是多少,

但是想让z变成只有一列,行数不知道多少,

通过z.reshape(-1,1),Numpy自动计算出有16行,

新的数组shape属性为(16,1),与原来的(4,4)配套。

[[ 1]
[ 2]
[ 3]
[ 4]
[ 5]
[ 6]
[ 7]
[ 8]
[ 9]
[10]
[11]
[12]
[13]
[14]
[15]
[16]]
print(z.reshape(2,-1))
[[ 1 2 3 4 5 6 7 8]
[ 9 10 11 12 13 14 15 16]]


<pre class="has">
>>> arr = np.arange(10)

np.random.shuffle(arr)
arr
[1 7 5 2 9 4 3 6 0 8]
This function only shuffles the array along the first index of a multi-dimensional array:
arr = np.arange(9).reshape((3,3))
np.random.shuffle(arr)
arr
array([[3,5], [6, [0,2]])

返回一个随机排列

<pre class="has">
<code class="language-python">a=np.arange(9)
np.random.permutation(a)
Out[39]: array([0,6])
a
Out[40]: array([0,8])
b=np.arange(9).reshape((3,3))
b
Out[42]:
array([[0,[6,8]])
np.random.permutation(b)
Out[43]:
array([[6,[0,5]])
b
Out[44]:
array([[0,8]])


a = [[1,6]]
1.sum(map(sum,a) 函数是对a中的每一个元素进行sum操作
解释一下map函数, map(fund,a) equals
[func(i) for i in a] and return a list
2.sum(sum(i) for i in a) #second one
3.sum(sum(a[i]) for i in range(len(a))) #third one
4.reduce(lambda x,a))
解释一下reduce(fun,a),只不说reduce返回的是一个结果值而不是一个list,第一步的时候是([1,2]+[3,4]) + [5,6]
得到一个[1,2,3,4,5,6], 然后进行的运算是(((((1+2)+3)+4)+5)+6) = 21

功能:从一维数组a中以概率p抽取抽取元素,形成size形状新的数组,replace表示是否可以重用元素,默认为True。举例:

<pre class="has">
<code class="language-python">np.random.choice([0,1],(2,3),p=[0.1,0.9])
Out[14]:
array([[1,[1,1]])
np.random.choice([0,p=[0.5,0.5])
Out[15]:
array([[0,0.5])
Out[16]:
array([[0,0]])

本来是想打算使用eval函数对变量进行赋值的,没想到出现了invalid syntax错误。源代码如下

<table border="0" cellpadding="0" cellspacing="0" style="margin-left:0px;width:643px;">

    推荐文章
      热点阅读