python dataset用法_Python干货:26个python源代码,节省6小时

本文汇总了26个Python编程的实用技巧,包括十进制与二、八、十六进制的转换,字符串与字节类型互换,ASCII处理,浮点数转换,数据字典创建,排序、求和函数,用户输入,文件操作,迭代器创建等。适合Python初学者和进阶者提升技能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

干货满满,整理不容易!

55ba817a-7f28-eb11-8da9-e4434bdf6706.png

1.十进制转换为二进制

>>> bin(10)'0b1010'

2.十进制转换为八进制

>>> oct(9)'0o11'

3.十进制转换为十六进制

>>> hex(15)'0xf'

4.字符串转换为字节类型

>>> s = "apple">>> bytes(s,encoding='utf-8')b'apple'

5.字符类型、数值型等转换为字符串类型

>>> i = 100>>> str(i)'100'

6.十进制整数对应的 ASCII 字符

>>> chr(65)'A'

7.ASCII字符对应的十进制数

>>> ord('A')65

8.整数或数值型字符串转换为浮点数

>>> float(3)3.0

9.创建数据字典的几种方法

>>> dict(){}>>> dict(a='a',b='b'){'a': 'a', 'b': 'b'}>>> dict(zip(['a','b'],[1,2])){'a': 1, 'b': 2}>>> dict([('a',1),('b',2)]){'a': 1, 'b': 2}

10.排序函数

>>> a = [1,4,2,3,1]#降序>>> sorted(a,reverse=True)[4, 3, 2, 1, 1]>>> a = [{'name':'xiaoming','age':18,'gender':'male'},       {'name':'xiaohong','age':20,'gender':'female'}]#按 age升序>>> sorted(a,key=lambda x: x['age'],reverse=False)[{'name': 'xiaoming', 'age': 18, 'gender': 'male'}, {'name': 'xiaohong', 'age': 20, 'gender': 'female'}]

11.求和函数

>>> a = [1,4,2,3,1]>>> sum(a)11#求和初始值为1>>> sum(a,1)12

12.计算字符串型表达式的值

>>> s = "1 + 3 +5">>> eval(s)9>>> eval('[1,3,5]*3')[1, 3, 5, 1, 3, 5, 1, 3, 5]

13.获取用户输入内容

>>> input()I'm typing "I'm typing "

14.print 用法

>>> lst = [1,3,5]# f 打印>>> print(f'lst: {lst}')lst: [1, 3, 5]# format 打印>>> print('lst:{}'.format(lst))lst:[1, 3, 5]

15.格式化字符串常见用法

>>> print("i am {0},age {1}".format("tom",18))i am tom,age 18>>> print("{:.2f}".format(3.1415926)) # 保留小数点后两位3.14>>> print("{:+.2f}".format(-1)) # 带符号保留小数点后两位-1.00>>> print("{:.0f}".format(2.718)) # 不带小数位3>>> print("{:0>3d}".format(5)) # 整数补零,填充左边, 宽度为3005>>> print("{:,}".format(10241024)) # 以逗号分隔的数字格式10,241,024>>> print("{:.2%}".format(0.718)) # 百分比格式71.80%>>> print("{:.2e}".format(10241024)) # 指数记法1.02e+07

值(值得注意,自定义的实例都可哈希,list, dict, set等可变对象都不可哈希)

>>> class Student():      def __init__(self,id,name):        self.id = id        self.name = name        >>> xiaoming = Student('001','xiaoming')>>> hash(xiaoming)-9223371894234104688

16.if not x

直接使用 x 和 not x 判断 x 是否为 None 或空

x = [1,3,5]if x:    print('x is not empty ')if not x:    print('x is empty')

17.打开文件,并返回文件对象

>>> import os>>> os.chdir('D:/source/dataset')>>> os.listdir()['drinksbycountry.csv', 'IMDB-Movie-Data.csv', 'movietweetings', 'titanic_eda_data.csv', 'titanic_train_data.csv']>>> o = open('drinksbycountry.csv',mode='r',encoding='utf-8')>>> o.read()"country,beer_servings,spirit_servings,wine_servings,total_litres_of_pure_alcohol,continentAfghanistan,0,0,0,0.0,AsiaAlbania,89,132,54,4.9,"

18. 创建迭代器

>>> class TestIter(): def __init__(self,lst):  self.lst = lst   # 重写可迭代协议__iter__ def __iter__(self):  print('__iter__ is called')  return iter(self.lst)

迭代 TestIter 类:

>>> t = TestIter()>>> t = TestIter([1,3,5,7,9])>>> for e in t: print(e) __iter__ is called13579

19.创建range迭代器

>>> t = range(11)>>> t = range(0,11,2)>>> for e in t:     print(e)0246810

20.反向

>>> rev = reversed([1,4,2,3,1])>>> for i in rev: print(i) 13241

21.打包

>>> x = [3,2,1]>>> y = [4,5,6]>>> list(zip(y,x))[(4, 3), (5, 2), (6, 1)]>>> for i,j in zip(y,x): print(i,j)4 35 26 1

22.过滤器

函数通过 lambda 表达式设定过滤条件,保留 lambda 表达式为True的元素:

>>> fil = filter(lambda x: x>10,[1,11,2,45,7,6,13])>>> for e in fil:       print(e)114513

23. split 分割**

>>> 'i love python'.split(' ')['i', 'love', 'python']

24. 提取后缀名

>>> import os>>> os.path.splitext('D:/source/dataset/new_file.txt')('D:/source/dataset/new_file', '.txt') #[1]:后缀名

25.斐波那契数列前n项

>>> def fibonacci(n):      a, b = 1, 1      for _ in range(n):        yield a        a, b = b, a+b # 注意这种赋值>>> for fib in fibonacci(10):      print(fib) 11235813213455

26.list 等分 n 组

>>> from math import ceil>>> def divide_iter(lst, n):      if n <= 0:        yield lst        return      i, div = 0, ceil(len(lst) / n)      while i < n:        yield lst[i * div: (i + 1) * div]        i += 1  >>> for group in divide_iter([1,2,3,4,5],2):      print(group) [1, 2, 3][4, 5]

我这里还有很多关于python爬虫,人工智能,数据分析,web开发方面的教程以及资料,如果很多自学的同学或者想学的同学可以在评论区评论“我要干货”就可以领取! 希望大家好好学习!更加努力!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值