python常用数值类型及方法

数值类型

iterable:list、tuple、string、set、dict

dict

以下是字典的一些常见操作和用法:

创建字典:可以使用大括号 {} 和冒号 : 来创建字典,键值对之间用逗号 , 分隔。
person = {“name”: “Alice”, “age”: 25, “city”: “New York”}
访问字典中的值:可以使用键来访问字典中的值。
print(person[“name”]) # 输出: “Alice”
print(person[“age”]) # 输出: 25
添加或修改键值对:可以通过指定键来添加或修改字典中的键值对。
person[“occupation”] = “Engineer” # 添加键值对
person[“age”] = 26 # 修改值
删除键值对:可以使用 del 关键字删除字典中的键值对。
del person[“city”] # 删除键为 “city” 的键值对
字典方法:字典对象提供了一些有用的方法,如 keys()、values() 和 items(),用于返回字典的键、值和键值对。
keys = person.keys() # 返回所有键
values = person.values() # 返回所有值
items = person.items() # 返回所有键值对
遍历字典:可以使用 for 循环遍历字典的键或键值对。
for key in person:
print(key, person[key])

或者使用 items() 方法遍历键值对

for key, value in person.items():
print(key, value)

set

#初始化
a=set{}
my_set = {1, 2, 3}  # 使用花括号创建集合
my_set = {1, 2, 3}
my_set.add(4)  # 向集合中添加单个元素
my_set.update([5, 6])  # 向集合中添加多个元素
my_set = {1, 2, 3}
my_set.add(4)  # 向集合中添加单个元素
my_set.update([5, 6])  # 向集合中添加多个元素
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)  # 并集
intersection_set = set1.intersection(set2)  # 交集
difference_set = set1.difference(set2)  # 差集
symmetric_difference_set = set1.symmetric_difference(set2)  # 对称差集
my_set = {1, 2, 3}
print(2 in my_set)  # 输出 True
print(4 in my_set)  # 输出 False



my_set = {1, 2, 3, 4, 5}

my_set.remove(3)  # Removes the element 3 from the set

print(my_set)  # Output: {1, 2, 4, 5}

list

常用方案

append

append() 方法用于在列表末尾添加一个元素。它接受一个参数,即要添加的元素,并将其追加到列表的末尾。例如:

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # 输出: [1, 2, 3, 4]

切片

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 获取索引为2到索引为5(不包含)的子序列
sub_list = my_list[2:5]
print(sub_list)  # 输出 [3, 4, 5]

# 获取从索引为1开始到末尾的子序列
sub_list = my_list[1:]
print(sub_list)  # 输出 [2, 3, 4, 5, 6, 7, 8, 9, 10]

# 获取从开头到索引为7(不包含)的子序列,步长为2
sub_list = my_list[:7:2]
print(sub_list)  # 输出 [1, 3, 5, 7]

# 反转整个列表
reversed_list = my_list[::-1]
print(reversed_list)  # 输出 [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]


insert(index, element): 在指定的索引位置插入一个元素。

my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list)  # 输出: [1, 4, 2, 3]

remove(element): 移除列表中第一个匹配的指定元素。

my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list)  # 输出: [1, 3, 2]

index(element): 返回列表中第一个匹配指定元素的索引。

my_list = [1, 2, 3, 2]
index = my_list.index(2)
print(index)  # 输出: 1

count(element): 返回指定元素在列表中出现的次数。

my_list = [1, 2, 3, 2]
count = my_list.count(2)
print(count)  # 输出: 2

sort(): 对列表进行排序(默认升序)。

my_list = [3, 1, 4, 2]
my_list.sort()
print(my_list)  # 输出: [1, 2, 3, 4]

reverse(): 反转列表中的元素顺序。

my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list)  # 输出: [4, 3, 2, 1]

extend(iterable): 将可迭代对象中的元素添加到列表末尾。

my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list)  # 输出: [1, 2, 3, 4, 5]

pop

pop() 方法用于从列表中移除并返回指定位置的元素。它可以接受一个可选参数,即要移除的元素的索引。如果未提供索引,则默认移除并返回列表的最后一个元素。例如:

my_list = [1, 2, 3, 4]
removed_element = my_list.pop(2)
print(removed_element)  # 输出: 3
print(my_list)  # 输出: [1, 2, 4]

#如果不提供索引参数,直接调用 pop() 方法会移除并返回列表的最后一个元素:
my_list = [1, 2, 3, 4]
removed_element = my_list.pop()
print(removed_element)  # 输出: 4
print(my_list)  # 输出: [1, 2, 3]
#需要注意的是,pop() 方法会改变原始列表,同时返回被移除的元素

##ListNode

class ListNode:
    def __init__(self, value=0, next_node=None):
        self.val = value
        self.next = next_node

class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        dummy = ListNode()
        current = dummy
        carry = 0
        
        node1 = l1
        node2 = l2
        
        while node1 or node2 or carry:
            sum_val = (node1.val if node1 else 0) + (node2.val if node2 else 0) + carry
            carry = sum_val // 10
            current.next = ListNode(sum_val % 10)
            current = current.next
            
            node1 = node1.next if node1 else None
            node2 = node2.next if node2 else None
        
        return dummy.next

常用方法

sorted

可以用于对以下数值类型进行排序:
list、tuple、string、set、dict

Sorted(a,reverse=True)  #降序
b = sorted(a.items, key=lambda x: x[2])

sorted("7896") #输出['6', '7', '8', '9']

lambda

def multiplier(n):
    return lambda x: x * n

double = multiplier(2)
triple = multiplier(3)

print(double(5))  # 输出: 10
print(triple(5))  # 输出: 15

try … except…

enumerate(str)

for i, char in enumerate(s):,enumerate() 被用来迭代字符串 s 中的字符。变量 i 表示当前字符的索引,char 表示当前字符的值。这样你就可以在迭代过程中同时访问每个元素的索引和值。

map

map(function, iterable)


a, b = map(int,input().split())
numbers = [1, 2, 3, 4, 5]

def double(x):
    return x * 2

result = map(double, numbers)

print(list(result))
#输出[2, 4, 6, 8, 10]

注意事项

1.for i in k:

k必须是一个可迭代元素,而不能是一个数字

2.整除//

求余%

3.判断输入结束:

while(true):
	try:
	...
	catch:
	    break;

while (true):
    if():
        break


n,m=map(int,input().split())

4.进制转换

decimal_number = 42
binary_number = bin(decimal_number)  # 转换为二进制
octal_number = oct(decimal_number)  # 转换为八进制
hexadecimal_number = hex(decimal_number)  # 转换为十六进制

print(binary_number)  # 输出 '0b101010'
print(octal_number)  # 输出 '0o52'
print(hexadecimal_number)  # 输出 '0x2a'

binary_number = '101010'
octal_number = '52'
hexadecimal_number = '2a'

decimal_number1 = int(binary_number, 2)  # 转换二进制为十进制
decimal_number2 = int(octal_number, 8)  # 转换八进制为十进制
decimal_number3 = int(hexadecimal_number, 16)  # 转换十六进制为十进制

print(decimal_number1)  # 输出 42
print(decimal_number2)  # 输出 42
print(decimal_number3)  # 输出 42


4。函数变量

在 Python 中,函数可以访问全局作用域中的变量,但在函数内部修改全局变量的值需要使用 global 关键字。在给定的代码中,m 和 n 并没有被声明为全局变量,所以在函数内部并不需要使用 global 关键字

5.for-else

for item in iterable:
    # 循环体
    if condition:
        # 条件满足时的操作
        break
else:
    # 循环完整执行且没有遇到 break 时的操作

5.深度搜索迷宫


def dfs(i,j):
    dx = [0,0,-1,1]
    dy = [-1,1,0,0]
    if i == m-1 and j == n-1:
        for pos in route:
            print('('+str(pos[0])+','+str(pos[1])+')')
        return
    
    for k in range(4):
        x = i+dx[k]
        y = j+dy[k]
        if x>=0 and x<m and y>=0 and y<n and map1[x][y]==0:
            map1[x][y]=1
            route.append((x,y))
            dfs(x,y)
            map1[x][y]=0
            route.pop()
    else:
        return
            

while True:
    try:
        m,n = list(map(int,input().split()))
        map1=[]
        for i in range(m):
            s=list(map(int,input().split()))
            map1.append(s)
        route = [(0,0)]
        map1[0][0]=1
        dfs(0, 0)
        
    except:
        break
data  = input().split()
row, col = int(data[0]), int(data[1])

dp = [[1 for m in range(col+1)] for n in range(row+1)]

for i in range(1, row+1):
    for j in range(1, col+1):
        dp[i][j] = dp[i][j-1]+dp[i-1][j]

print(dp[row][col])

滑动窗口

import sys
from collections import Counter, defaultdict
 
def count_kelegant_subarrays(arr_len, k_value, arr_elements):
    result = 0
    left = 0
    right = 0
    element_count = {}
 
    while (left < arr_len and right < arr_len):
        current_element = arr_elements[right]
        
        if (current_element in element_count):
            element_count[current_element] += 1
        else:
            element_count[current_element] = 1
 
        if (element_count[current_element] >= k_value):
            result += arr_len - right
            element_count[arr_elements[left]] -= 1
            left += 1
            element_count[current_element] -= 1
            right -= 1
        right += 1
 
    return result
 
input_params = [int(x) for x in input().split(" ")]
arr_len = input_params[0]
k_value = input_params[1]
arr_elements = [int(x) for x in input().split(" ")]
 
print(count_kelegant_subarrays(arr_len, k_value, arr_elements))

7.数组批量生成

arr = [0] * 50
print(arr)

火车进站

res = []  # 保存搜索结果的列表

def dfs(wait, stack, out):
    if not wait and not stack:
        res.append(' '.join(map(str, out)))  # 如果待处理列表和栈都为空,将结果转化为字符串并保存到 res 列表中

    if wait:  # 如果待处理列表不为空,将待处理列表的第一个元素入栈
        dfs(wait[1:], stack + [wait[0]], out)

    if stack:  # 如果栈不为空,将栈顶元素出栈
        dfs(wait, stack[:-1], out + [stack[-1]])

while True:
    try:
        n, nums = int(input()), list(map(int, input().split()))
        dfs(nums, [], [])  # 调用 dfs 函数进行深度优先搜索
        for i in sorted(res):  # 对搜索结果进行排序并输出
            print(i)
    except:
        break
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值