python[:]访问元素
包头不包尾
a = [1, 2, 3, 4, 5]
print(a[-1]) # 倒数第一个元素
print(a[-2]) # 倒数第二个元素
print(a[-2:-1])
print(a[-5:-2]) # 包头不包尾
print(a[2::-1]) # 从0到2元素逆序输出
print(a[:-1]) # 包头不包尾,处了倒数第一个元素
print(a[::-1]) # 逆序输出
结果:
item函数
items() 方法把字典中每对 key 和 value 组成一个元组,并把这些元组放在列表中返回。
print(len({"11": "racehorse", "22": "ditto"}.items()))
d = {'one': 1, 'two': 2, 'three': 3}
print(d.items())
实现矩阵乘法
def matrixMul(A, B):
if len(A[0]) == len(B):
res = [[0] * len(B[0]) for _ in range(len(A))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
res[i][j] += A[i][k] * B[k][j]
return res
return '输入矩阵有误!'
n, m, k = map(int, input().split())
array = []
array1 = []
array_result = []
for i in range(n):
temp = []
temp = list(map(int, input().split()))
array.append(temp)
for i in range(m):
temp = []
temp = list(map(int, input().split()))
array1.append(temp)
array_result = matrixMul(array, array1)
for i in range(len(array_result)):
for j in range(len(array_result[0])):
print(array_result[i][j], end=" ")
print()
结果:
实现栈
class Stack:
def __init__(self):
self.sizes = 10000
self.stack = []
def push(self, item):
if len(self.stack) <= self.sizes:
self.stack.append(item)
else:
raise Exception("stack is full!")
def pop(self):
if self.is_empty():
raise Exception("stack is empty!")
else:
return self.stack.pop()
def peek(self):
if self.is_empty():
raise Exception("stack is empty!")
else:
return self.stack[-1]
def is_empty(self):
if len(self.stack) == 0:
return True
else:
return False
def size(self):
return len(self.stack)
a = Stack()
a.push(2)
a.push(3)
a.push(4)
print(a.peek())
print(a.pop())
print(a.is_empty())
print(a.size())
结果:
实现队列
class Queue:
def __init__(self):
self.sizes = 10000
self.queue = []
def enqueue(self, item):
if len(self.queue) <= self.sizes:
self.queue.append(item)
else:
raise Exception("stack is full!")
def dequeue(self):
if self.is_empty():
raise Exception("stack is empty!")
else:
return self.queue.pop(0)
def is_empty(self):
if len(self.queue) == 0:
return True
else:
return False
def size(self):
return len(self.queue)
a = Queue()
a.enqueue(2)
a.enqueue(3)
a.enqueue(4)
print(a.dequeue())
print(a.dequeue())
print(a.is_empty())
print(a.size())
结果:
质数分解
from functools import reduce
def test(num, l=[]):
a = True
for i in range(2, num):
if num % i == 0:
a = False
n = num // i
l.append(i)
break
if a:
l.append(num)
return str(reduce(lambda x, y: x * y, l)) + ' = ' + ' * '.join([str(i) for i in l])
else:
return test(n, l)
m = int(input())
a = test(m)
print(a)
结果:
给定一个十进制正整数,根据数制转换的原理将其转换成对应的k进制(2<=k<=9)
def transform(num, k):
list1 = []
while num != 0:
list1.append(num % k)
num //= k
return list1
n = int(input())
k = int(input())
array = transform(n, k)
array = array[::-1]
for i in array:
print(i, end="")
结果: