pyton基础知识积累

1、reshape函数的应用

import numpy as np

z = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])
z.shape
print (z.shape)
z = np.reshape(z,(-1))
print (z.shape)
z = np.reshape(z,(2,-1))#当指定行数2之后,列数设置为-1为default,会在满足行数的情况下设置列数
print (z.shape)

打印结果:

    (4, 4)
    (16,)
    ( 2, 8)

其它网上的做法达不到预期的效果,故留做备忘

2、字典使用(dictionary)

参考网站

    #创建字典
    #字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:
    #d = {key1 : value1, key2 : value2 }

    #要点一个key可以对应多个value,反之一个value只能对应一个key
    #value可以取任何数据类型,但key必须是不可变的,如字符串,数字或元组。
    dict = {'Name': 'xiaohui', 'Age': 7, 'Class': 'First',123:'hello'};#'Name'字符串 123数字  元组不知道是什么鬼
    #通过key访问value
    print (dict['Name']) #xiaohui
    #通过key修改value
    dict['Age'] = 8
    print (dict['Age']) #8
    del dict['Name']; # 删除键是'Name'的条目
    print (dict)       #{123: 'hello', 'Class': 'First', 'Age': 8}

    #dict.clear();     # 清空词典所有条目
    #del dict ;        # 删除词典

3、dictionary和json转换

# coding= utf-8
import json
import sys

if __name__ == '__main__':
    # 将python对象test转换json对象
    test = {"username":"测试","age":16}#其中username为key,测试 为value
    print ('test 类型:',type(test)) #test 类型: <class 'dict'>
    print (test)                    #{'username': '测试', 'age': 16}
    
    python_to_json = json.dumps(test,ensure_ascii=False)
    print ('将python转换为json类型:',type(python_to_json)) #将python转换为json类型: <class 'str'>
    print (python_to_json)                               #{"username": "测试", "age": 16}

    
    # 将json对象转换成python对象
    json_to_python = json.loads(python_to_json)
    print ('将json转换为python类型:',type(json_to_python))#将json转换为python类型: <class 'dict'>
    print (json_to_python['username'])#根据key 获取value

    print ("输出所有的value:%s"%json_to_python.values())#输出所有的value:dict_values(['测试', 16])
    print ("输出所有的key:%s"%json_to_python.keys()) #输出所有的key:dict_keys(['username', 'age'])

4、将dictionary中的key和value互换

    dictionary = {'Name': 'xiaohui', 'Age': 7, 'Class': 'First','123':'hello',"0615":"生日快乐","出生年份":"1992"};#'Name'字符串 123数字  元组不知道是什么鬼
    i = 123
    print (str(i))#一个小的trick,输入元素i为123的时候,那么str(i)则为‘123’
    print (dictionary[str(i)])#通过str(i)则可访问'123',否则会无法识别123报KeyError: 123
    #print (dictionary[i])#报KeyError: 123

    #将key和value互换
    #方法一:
    dictionary_new1 = {value:key for key,value in dictionary.items()}
    print ('dictionary_new1:',dictionary_new1)
    #dictionary_new1: {'hello': '123', '1992': '出生年份', 'First': 'Class', 'xiaohui': 'Name', '生日快乐': '0615', 7: 'Age'}

    #方法二:
    dictionary_new2 = dict( zip( dictionary.values(),dictionary.keys() ) )
    print ('dictionary_new2:',dictionary_new2)
    #dictionary_new1: {'hello': '123', '1992': '出生年份', 'First': 'Class', 'xiaohui': 'Name', '生日快乐': '0615', 7: 'Age'}

5、json文件的读取与保存

dictionary = {'Name': 'xiaohui', 'Age': 7, 'Class': 'First','123':'hello',"0615":"生日快乐","出生年份":"1992"}
dictionary_json = json.dumps(dictionary,ensure_ascii=False)#ensure_ascii=False则表示输出真正的中文
print (dictionary_json)   #{"出生年份": "1992", "123": "hello", "0615": "生日快乐", "Class": "First", "Name": "xiaohui", "Age": 7}

#json.dump()函数的使用,将json文件保存
with open("./test.json","w",encoding='utf-8') as f:
    json.dump(dictionary_json,f)
#./test.json文件内容如下
#"{\"\u51fa\u751f\u5e74\u4efd\": \"1992\", \"123\": \"hello\", \"0615\": \"\u751f\u65e5\u5feb\u4e50\", \"Class\": \"First\", \"Name\": \"xiaohui\", \"Age\": 7}"

# json.load()函数的使用,将读取json信息
file = open('./test.json','r',encoding='utf-8')
file_to_json = json.load(file)
print(file_to_json)
#{"出生年份": "1992", "123": "hello", "0615": "生日快乐", "Class": "First", "Name": "xiaohui", "Age": 7}

6、python的换行

print ()#print ()表示换一行
print('\n' *1)#print('\n' * n)  n表示换几行;python3可以,python2不可以


7、list 相关的函数

extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。

aList = [123, 'xyz', 'zara', 'abc', 123];
bList = [2009, 'manni'];
aList.extend(bList)

print ("Extended List : ", aList)
#Extended List :  [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']

8、python 的collections的使用

主要用于统计list的单词出现的频率

import collections

#申请list类型的变量
count = [['UNK', -1]]
print (type(count))#<class 'list'>
print ('old count',count)#old count [['UNK', -1]]
words = ['笛', '岳','笛','笛','笛','笛','笛','笛','岳','岳','阳','阳','阳', '楼', '外',  '天', '远', '霞', '红']
tt = collections.Counter(words) #统计单词列表重单词的频数
print (tt)#将统计结果打印出来,统计结果如下
#Counter({'笛': 7, '岳': 3, '阳': 3, '远': 1, '外': 1, '楼': 1, '霞': 1, '天': 1, '红': 1})
print (type(tt))#<class 'collections.Counter'>
print (tt['笛'])#打印莫个词重复的频数  7

most_common_tt = collections.Counter(words).most_common(3)#将统计单词列表重单词的频数中前3个赋给most_common_tt
print ('most_common_tt:',most_common_tt)#most_common_tt: [('笛', 7), ('阳', 3), ('岳', 3)]

9、python 的global

# coding= utf-8

global_variable = 0

def test_global():
    global global_variable

    print ('in the function test_global and before',global_variable)
    global_variable = 10
    print ('in the function test_global and after',global_variable)
print ('before function test_global',global_variable)
test_global()
print ('after function test_global',global_variable)
#输出如下:
#before function test_global 0
#in the function test_global and before 0
#in the function test_global and after 10
#after function test_global 10

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值