0
点赞
收藏
分享

微信扫一扫

多维列表


1、初始化

import random
matrix=[]
numberOfRows=eval(input("Enter the number of rows:"))
numberOfColumns=eval(input("Enter the number of the columns"))
for row in range(numberOfRows):
matrix.append([])
for column in range(numberOfColumns):
# matrix[row].append(random.randint(0,99))
matrix[row].append(column*row)

2、打印

for row in range(len(matrix)):
for value in matrix[row]:
print(value,end=" ")
print()

3、总体求和

totalValue=0
for row in range(len(matrix)):
for value in matrix[row]:
totalValue+=value
print("totalValue=",totalValue)

4、按列求和

total=[]
for column in range(len(matrix[0])):
totalValue=0
for row in range(len(matrix)):
totalValue+=matrix[row][column]
total.append(totalValue)
print(total)

5、找最大行

index=0
maxRow=sum(matrix[0])
for row in range(1,len(matrix)):
if maxRow<sum(matrix[row]):
index=row
maxRow=sum(matrix[row])
print("the sum of matrix [",index,"] is the maxValue ",maxRow)

6、打乱

for row in range(numberOfRows):
for column in range(numberOfColumns):
i=random.randint(0,numberOfRows-1)
j=random.randint(0,numberOfColumns-1)
matrix[i][j],matrix[row][column]=matrix[row][column], matrix[i][j]
print(matrix)

7、排序

‘’’
sort()规则是:通过每行第一个元素排序,如果第一个元素相同,则比较后面一个元素
‘’’

matrix.sort()
print(matrix)

8.实例:找距离最近的2个点

def main():
points = [[-1, 3],
[-1, -1],
[1, 1],
[2, 0.5],
[2, -1],
[3, 3],
[4, 2],
[4, -0.5]]
x, y = nearestPoints(points)
print("one team of the nearestPoints are ", points[x], " and ", points[y])


def distance(x1, y1, x2, y2):
return ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5


def nearestPoints(points):
p1, p2 = 0, 1
shortestDistance = distance(points[p1][0], points[p1][1],
points[p2][0], points[p2][1])

for i in range(len(points)):
for j in range(i + 1, len(points)):
d = distance(points[i][0], points[i][1],
points[j][0], points[j][1])
if shortestDistance > d:
p1, p2 = i, j
shortestDistance = d
return p1, p2


main()

多维列表_ooc

9、实例:鼠标左击创建点,找最短距离的2个点画线

NearestPoints.py如下:

def distance(x1, y1, x2, y2):
return ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5


def nearestPoints(points):
p1, p2 = 0, 1
shortestDistance = distance(points[p1][0], points[p1][1],
points[p2][0], points[p2][1])

for i in range(len(points)):
for j in range(i + 1, len(points)):
d = distance(points[i][0], points[i][1],
points[j][0], points[j][1])
if shortestDistance > d:
p1, p2 = i, j
shortestDistance = d
return p1,

"""
鼠标左击创建点,找彼此距离最近的2个点
"""
import NearestPoints
from tkinter import *

RADIUS = 2

class NearestPointsGUI:
def __init__(self):
self.points = []
window = Tk()
window.title("Finde Nearest Points")

self.canvas = Canvas(window)
self.canvas.pack()

self.canvas.bind("<Button-1>", self.addPoint)
window.mainloop()


def addPoint(self, event):
if not self.isTooCloseOtherPoints(event.x,event.y):
self.addThePoint(event.x,event.y)

def addThePoint(self, x, y):
self.canvas.create_oval(x - RADIUS, y - RADIUS, x + RADIUS, y + RADIUS)
self.points.append([x, y])
if len(self.points) >= 2:
p1, p2 = NearestPoints.nearestPoints(self.points)
self.canvas.delete("line")
self.canvas.create_line(self.points[p1][0], self.points[p1][1], self.points[p2][0], self.points[p2][1],
tags="line")

def isTooCloseOtherPoints(self, x, y):
for i in range(len(self.points)):
if NearestPoints.distance(x, y, self.points[i][0], self.points[i][1]) <= RADIUS + 2:
return True
return False

NearestPointsGUI()

多维列表_初始化_02

10、数独判断可视化

from tkinter import *
import tkinter.messagebox


def isValid(grid):
for i in range(9):
for j in range(9):
if grid[i][j] < 1 or grid[i][j] > 9 or not isValidate(i, j, grid):
return False
return True


def isValidate(i, j, grid):
for column in range(len(grid[0])):
if column != j and grid[i][column] == grid[i][j]:
return False
for row in range(len(grid)):
if row != i and grid[row][j] == grid[i][j]:
return False
for row in range((i // 3) * 3, (i // 3) * 3 + 3):
for col in range((j // 3) * 3, (j // 3) * 3 + 3):
if row != i and col != j and grid[i][j] == grid[row][col]:
return False
return True


class SudoGUI:
def __init__(self):
window = Tk()
window.title("Check Sudo Soluntion ")

frame = Frame(window)
frame.pack()

self.cells = []
for i in range(9):
self.cells.append([])
for j in range(9):
self.cells[i].append(StringVar())
# self.cells[0][0].set("1") #可以这样设置某些格的数字,形成待填的表格




for i in range(9):
for j in range(9):
Entry(frame, width=2, justify=RIGHT, textvariable=self.cells[i][j]).grid(row=i, column=j)

Button(window, text="Validate", command=self.validate).pack()
window.mainloop()

def validate(self):
values = [[eval(x.get()) for x in self.cells[i]] for i in range(9)]
if isValid(values):
tkinter.messagebox.showinfo("Check SuDu Solution","Valid")
else:
tkinter.messagebox.showwarning("Check SuDu Solution","inValid")

SudoGUI()

多维列表_ooc_03

11猜出生是几号

def getDates():
return [
[[1, 3, 5, 7], [9, 11, 13, 15], [17, 19, 21, 23], [25, 27, 29, 31]],
[[2, 3, 6, 7], [10, 11, 14, 15], [18, 19, 22, 23], [26, 27, 30, 31]],
[[4, 5, 6, 7], [12, 13, 14, 15], [20, 21, 22, 23], [28, 29, 30, 31]],
[[8, 9, 10, 11], [12, 13, 14, 15], [24, 25, 26, 27], [28, 29, 30, 31]],
[[16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31]]
]


def guess(dates):
day = 0
for i in range(5):
print("Is your birthday in Set" + str(i + 1) + "?")
for j in range(4):
for k in range(4):
print(format(dates[i][j][k], "4d"), end=" ")
print()
answer = eval(input("Enter 0 for No ,1 for yes:"))
if answer == 1:
day += dates[i][0][0]
return day


def main():
day = 0
dates = getDates()
print("生日是", str(guess(dates)))


main()

12、矩阵加、乘运算

def createMatrix():
row, column = map(eval, input("Enter maxtrix 's row and column").split(" "))

m = input("Enter maxtrix1:")
matrxi = []
time = 1
for i in range(row):
matrxi.append([])
for j in range(column):
matrxi[i].append(eval((m.strip().split())[time - 1]))
time += 1
return matrxi


def addMatrxi(m1, m2):
if len(m1[0]) != len(m2[0]) or len(m1) != len(m2):
print("维度不合适,不能操作")
else:
result = []
for i in range(len(m1)):
result.append([])
for j in range(len(m1[0])):
result[i].append( m1[i][j]+m2[i][j])
return result

def mulMatrxi(m1,m2):
if len(m1[0]) != len(m2):
print("维度不合适,不能操作")
else:
result=[]
for i in range(len(m1)):# 0
result.append([])
for k in range(len(m2[0])):
Result =0
for j in range(len(m1[0])):
Result =Result + m1[i][j]*m2[j][k]
result[i].append(Result)
return result


def showMatrix(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print(format(m1[i][j],">.1f"), end=" ")
print()

def showAddResult(m1,m2,result):
for i in range(len(result)):
for j in range(len(m1[0])):
print(format(m1[i][j],">.1f"),end=" ")

if i == len(m1)//2:
print(" +",end="")
else :
print("\t",end=" ")

for j in range(len(m2[0])):
print(format(m2[i][j],">.1f"),end=" ")

if i == len(m1)//2:
print(" = ",end="")
else :
print("\t",end=" ")

for j in range(len(result[0])):
print(format(result[i][j],">.1f"),end=" ")

print()

def showMulResult(m1,m2,result):
for i in range(len(result)):
for j in range(len(m1[0])):
print(format(m1[i][j],">.1f"),end=" ")

if i == len(m1)//2:
print(" *",end="")
else :
print("\t",end=" ")

for j in range(len(m2[0])):
print(format(m2[i][j],">.1f"),end=" ")

if i == len(m1)//2:
print(" = ",end="")
else :
print("\t",end=" ")

for j in range(len(result[0])):
print(format(result[i][j],">.1f"),end=" ")

print()

def main():
m1 = createMatrix()
m2 = createMatrix()
result=mulMatrxi(m1,m2)
showMulResult(m1,m2,result)
main()

# 1 2 3 4 5 6 11 8 11
# 0 2 4 1 4.5 2.2 1.1 4.3 5.2

多维列表_ooc_04


举报

相关推荐

0 条评论