Skip to content

获取系统类型

python
import platform
print(platform.system())
print(platform.release())

获取ip

python
import socket
# 获取本机计算机名称

hostname = socket.gethostname()

# 获取本机ip

ip = socket.gethostbyname(hostname)

print(ip)

批量检测端口开放
import os
import socket
def IsOpen(ip,port):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        s.connect((ip,int(port)))
        s.shutdown(2)
        print ("%d is open" % port)
        return True
    except:
        return False
if __name__ == '__main__':
    hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
i=1
while i < 5:
    print (i)
    print(ip)
    IsOpen('ip',i)
    i+=1

获取外网ip

python
import requests
ip = requests.get('https://checkip.amazonaws.com').text.strip()
print(ip)

获取运行时间

python
# ctypes required for using GetTickCount64()
import ctypes
 
# getting the library in which GetTickCount64() resides
lib = ctypes.windll.kernel32
 
# calling the function and storing the return value
t = lib.GetTickCount64()
 
# since the time is in milliseconds i.e. 1000 * seconds
# therefore truncating the value
t = int(str(t)[:-3])
 
# extracting hours, minutes, seconds & days from t
# variable (which stores total time in seconds)
mins, sec = divmod(t, 60)
hour, mins = divmod(mins, 60)
days, hour = divmod(hour, 24)
 
# formatting the time in readable form
# (format = x days, HH:MM:SS)
print(f"{days} days, {hour:02}:{mins:02}:{sec:02}")

调用shell

python
import os
os.system()

获取指定目录下文件名字

python
#-*- coding: UTF-8 -*-

import os

print (os.listdir("C:\\Users\Administrator\desktop"))
python
import os

print('***获取当前目录***')
print("当前目录是:{}".format(os.getcwd()))
print("当前目录是:{}".format(os.path.abspath(os.path.dirname(__file__))))

print('***获取上级目录***')
print("上级目录是:{}".format(os.path.abspath(os.path.dirname(os.path.dirname(__file__)))))
print("上级目录是:{}".format(os.path.abspath(os.path.dirname(os.getcwd()))))
print("上级目录是:{}".format(os.path.abspath(os.path.join(os.getcwd(), ".."))))

print('***获取上上级目录***')
print("上上级目录是:{}".format(os.path.abspath(os.path.join(os.getcwd(), "../.."))))

判断文件是否存在

python
import os
print(os.path.exists("C:\Windows\SysWOW64\cmd.exe"))

找到文件并读取文本内容

python
# -*- coding: UTF-8 -*-
import os
dir = "C:\\Users\Administrator\desktop"
filmname = "start.bat"
print(os.listdir(dir))
film = dir+'/'+filmname
try:
    f = open(film)
    while 1:
        lines = f.readlines(50)
        if not lines:
            break
        for line in lines:
            print(line)
    f.close()
except IOError:
    print("----------File is not accessible.")

读取文件大小

python
#-*- coding: UTF-8 -*-
import os
import string
def get_FileSize(filePath):
    fsize = os.path.getsize(filePath)
    fsize = fsize/float(1024*1024)
    return round(fsize,2)
if __name__ == '__main__':
    flim = "C:\\Users\diyworld\desktop"
    flimname = "1.py"
    print (os.listdir(flim))
try:
    print (get_FileSize(flim +'/'+ flimname))
except IOError:
    print("----------File is not accessible.")

判断端口是否开放

python
import os
import socket
def IsOpen(ip,port):
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    try:
        s.connect((ip,int(port)))
        s.shutdown(2)
        print ("%d is open" % port)
        return True
    except:
        print ("%d is down" % port)
        return False
if __name__ == '__main__':
    IsOpen('127.0.0.1',25255)

过CF

python
import requests


s = requests.Session()
url = 'https://dyxs25.com/show-231309/'

headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
}

html = s.get(url,headers=headers).text

input类型转换

如果输入的是小数,需要写成a = float(input("请输入一个小数"))。因为输入的默认按照str类型,而int函数只能转换数字类型的。

int(input())中输入10.2其实是int('10.2'),而不是int(10.2)

如果想把小数或整数都转换成整数,可以 写成a = int(float(input("请输入一个整数:")))

处理列表

在 Python 中使用列表的时候,你经常都需要向列表中添加新元素。

Python 列表数据类型 有三种方法向里面添加元素:

python
append() - 将一个元素附加到列表中
extend() - 将很多元素附加到列表中
insert() - 将一个元素插入列表指定位置

三元运算符

使用 if else 实现三目运算符(条件运算符)的格式如下:

python
exp1 if contion else exp2

condition 是判断条件,exp1 和 exp2 是两个表达式。如果 condition 成立(结果为真),就执行 exp1,并把 exp1 的结果作为整个表达式的结果;如果 condition 不成立(结果为假),就执行 exp2,并把 exp2 的结果作为整个表达式的结果。

在 for 遍历中改变列表

python
letter=['A','B','C','D','D','D']
for i in letter:

    if  i=='D':
       letter.remove(i)

print(letter)


=>['A','B','C','D']
python
letter = ['A', 'B', 'C', 'D', 'e', 'f']
for i in letter:
    print(i)
    if i == 'D':
        letter.remove(i)

print(letter)

=>
A
B
C
D
f
['A', 'B', 'C', 'e', 'f']

在for遍历时,i的值类似一个递归的数字,会在列表中以[0] [1] [2] [3]的顺序遍历。

这时如果移除列表中的元素,并不会影响i的取值,i依旧会循序递归下去,这样就会导致跳过部分值。

另一个例子:

python
import random
names = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
station = []
for i in range(len(names)):
    n = random.randint(0, len(names)-1)
    station.append(names[n])
    names.pop(n)
print(station)

在这里,因为range为不可变变量,所以不会因为len的长度变化而改变循环次数,而在上一个例子中遍历对象为可变变量,所以会因为其改变而影响遍历次数。

循环读取带空格和回车输入

python
while True:
    try:
        n = input()
        nums = n.split(" ")
        for i in nums:
            print(chr(int(i)), end="")
    except EOFError:
        break

for 循环多个参数

python
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]

for x, y, z in a, b, c:
    print(x, y, z)
    
output:
1 2 3
4 5 6
7 8 9

for x, y, z in zip(a, b, c):
    print(x, y, z)
    
output:
1 4 7
2 5 8
3 6 9

map函数

map 是 Python 内置的一个函数,用于对序列(如列表、元组等)中的每个元素执行相同的函数操作,并返回一个迭代器。这个函数接受两个参数:一个是函数,一个是可迭代对象。它会返回一个迭代器对象,每次迭代可以获取到经过函数操作处理后的元素。

例如,下面的代码将列表中的每个元素都加上 1:

python
scssCopy codenumbers = [1, 2, 3, 4, 5]
result = map(lambda x: x + 1, numbers)
print(list(result))  # [2, 3, 4, 5, 6]

在这个例子中,使用了 lambda 表达式定义了一个简单的函数,它把输入值加 1。然后使用 map 函数对 numbers 列表中的每个元素都执行了这个函数操作,最后得到一个迭代器对象 result。通过 list 函数可以将迭代器对象转换为列表,从而打印出结果 [2, 3, 4, 5, 6]

在上面的例子中,map 函数可以看作是一种便利方式,它可以将一个列表中的元素进行相同的操作,然后返回一个新的列表。而在上面的 PyTorch 代码中,我们使用 map 函数将多个 numpy 数组都转换为了 torch.Tensor 类型。这样做可以使得代码更加简洁和清晰。

一行for循环 (列表推导式)

定义

[expression for item in iterable if condition]

其中:

  • expression 是用于生成新列表元素的表达式。
  • item 是可迭代对象中的每个元素。
  • iterable 是一个可迭代对象,比如列表、元组、字符串等。
  • condition(可选)是一个条件表达式,用于过滤元素。
  1. 生成一个数字列表:
python
pythonCopy codenumbers = [x for x in range(10)]
# 输出: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. 对列表中的每个元素进行平方运算:
python
pythonCopy codesquares = [x**2 for x in numbers]
# 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  1. 过滤列表中的偶数:
python
pythonCopy codeeven_numbers = [x for x in numbers if x % 2 == 0]
# 输出: [0, 2, 4, 6, 8]
  1. 处理字符串列表,提取每个字符串的长度:
python
pythonCopy codestrings = ['hello', 'world', 'python']
lengths = [len(s) for s in strings]
# 输出: [5, 5, 6]
  1. 使用条件表达式生成一个新列表:
python
pythonCopy codegrades = [85, 92, 78, 90, 88]
result = ['pass' if grade >= 80 else 'fail' for grade in grades]
# 输出: ['pass', 'pass', 'fail', 'pass', 'pass']

pands 行列axis

首先请看一下官方帮助的解释:

轴用来为超过一维的数组定义的属性,二维数据拥有两个轴:第0轴沿着行的垂直往下,第1轴沿着列的方向水平延伸。

注意看,官方对于0和1的解释是轴,也就是坐标轴。而坐标轴是有方向的,所以千万不要用行和列的思维去想axis,因为行和列是没有方向的,这样想会在遇到不同的例子时感到困惑。

根据官方的说法,1表示横轴,方向从左到右0表示纵轴,方向从上到下当axis=1时,数组的变化是横向的,而体现出来的是列的增加或者减少。

其实axis的重点在于方向,而不是行和列。具体到各种用法而言也是如此。

当axis=1时,如果是求平均,那么是从左到右横向求平均;如果是拼接,那么也是左右横向拼接;如果是drop,那么也是横向发生变化,体现为列的减少。

Released under the MIT License.