Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何更改矩阵行中的最大和最小元素?_Python_Arrays_Python 3.x_Matrix - Fatal编程技术网

Python 如何更改矩阵行中的最大和最小元素?

Python 如何更改矩阵行中的最大和最小元素?,python,arrays,python-3.x,matrix,Python,Arrays,Python 3.x,Matrix,如何更改矩阵行中的最大和最小元素 下面我给出了我的代码,它不能正常工作,行中的最大和最小元素交换不正确,程序不稳定 number_of_rows = int(input("Enter the number of rows: ")) #matrix generator m = [[int(j) for j in input("Enter all the elements of a single row (separated by a space): ").s

如何更改矩阵行中的最大和最小元素

下面我给出了我的代码,它不能正常工作,行中的最大和最小元素交换不正确,程序不稳定

number_of_rows = int(input("Enter the number of rows: ")) #matrix generator
m = [[int(j) for j in input("Enter all the elements of a single row (separated by a space): ").split()] for i in range(number_of_rows)]
print("Your matrix : ", *m, sep = '\n')

    for i, row in enumerate(m):
        max = min = 0
        for j, elem in enumerate(row):
            if elem > row[max]:
                max = j
            if elem < row[min]:
                min = j
        row[max], row[0] = row[0], row[max]
        row[min], row[-1] = row[-1], row[min]
    print(m)
number_of_rows=int(输入(“输入行数”)#矩阵生成器
m=[[int(j)表示输入中的j(“输入单行的所有元素(用空格分隔):”)。split()]表示范围内的i(行数)]
打印(“您的矩阵:”,*m,sep='\n')
对于i,枚举中的行(m):
最大值=最小值=0
对于j,枚举中的元素(行):
如果元素>行[max]:
最大值=j
如果元素<行[min]:
min=j
行[max],行[0]=行[0],行[max]
行[min],行[-1]=行[-1],行[min]
打印(m)

我同意@Pranav Hosangadi关于变量使用min和max的评论。以下是我将如何执行矩阵交换功能:

for r, row in enumerate(m):
    mx_val = -float('inf')  #Sets max value to extremely low value to start
    mn_val = float('inf')   #Sets min_val to very high value to start
    mx_ptr = 0              # used to keep track of where in row max occurs
    mn_ptr = 0              #used to keep track of where min occurs
    for c, col in enumerate(row):           
        if col > mx_val:    #Test for col greater than current mx_val
            mx_ptr = c      # save the pointer
            mx_val = col    #save the value
        if col < mn_val:
            mn_ptr = c
            mn_val = col
    row[mn_ptr] = mx_val    #set row cell with mn_val to mx_val
    row[mx_ptr] = mn_val    #set row cell with mx_val to mn_val
print(m)    
对于r,枚举中的行(m):
mx_val=-float('inf')#将最大值设置为极低值以启动
mn_val=float('inf')#将min_val设置为非常高的启动值
mx_ptr=0#用于跟踪行中最大值出现的位置
mn_ptr=0#用于跟踪min发生的位置
对于c,枚举中的列(行):
如果col>mx_val:#测试col是否大于当前mx_val
mx_ptr=c#保存指针
mx_val=col#保存值
如果col
请创建一个。
max
min
在Python中已经有了意义。最好不要通过声明相同名称的变量来隐藏这些函数。我是否应该删除变量替换为max和min的行?谢谢,@itprorh66