反转 Python 中设置的函数
Inverse a function set in Python
我需要有关函数集作业的帮助。
我应该创建一个将函数集和 return 作为反函数集的方法。
一个函数集:
f = [[1,4],[2,5],[3,6]
应该return:
fInv = [[4,1],[5,2],[6,3]]
这是我的代码:
def inverse(f):
fInv = []
for i in range(len(f)):
count = len(f[0])
for j in range(len(f[0])):
fInv[i][j] = f[i][count]
count-=1
return fInv
return None
f = [[1,4],[2,5],[3,6]]
print(inverse(f))
当运行时,显示:
Traceback (most recent call last):
File "python", line 11, in <module>
File "python", line 5, in inverse
IndexError: list index out of range
我对使用 python 编码还很陌生,所以请理解问题可能是一个简单的逻辑错误。
尝试list.reverse()方法:
Reverse the elements of the list, in place.
f = [[1,4],[2,5],[3,6]]
for i in f:
i.reverse()
print f
输出:
[[4, 1], [5, 2], [6, 3]]
最简单的解决方案是使用列表推导解包每一对,然后以相反的顺序重新打包:
>>> f = [[1,4],[2,5],[3,6]]
>>> [[b, a] for [a, b] in f]
[[4, 1], [5, 2], [6, 3]]
我需要有关函数集作业的帮助。 我应该创建一个将函数集和 return 作为反函数集的方法。
一个函数集:
f = [[1,4],[2,5],[3,6]
应该return:
fInv = [[4,1],[5,2],[6,3]]
这是我的代码:
def inverse(f):
fInv = []
for i in range(len(f)):
count = len(f[0])
for j in range(len(f[0])):
fInv[i][j] = f[i][count]
count-=1
return fInv
return None
f = [[1,4],[2,5],[3,6]]
print(inverse(f))
当运行时,显示:
Traceback (most recent call last):
File "python", line 11, in <module>
File "python", line 5, in inverse
IndexError: list index out of range
我对使用 python 编码还很陌生,所以请理解问题可能是一个简单的逻辑错误。
尝试list.reverse()方法:
Reverse the elements of the list, in place.
f = [[1,4],[2,5],[3,6]]
for i in f:
i.reverse()
print f
输出:
[[4, 1], [5, 2], [6, 3]]
最简单的解决方案是使用列表推导解包每一对,然后以相反的顺序重新打包:
>>> f = [[1,4],[2,5],[3,6]]
>>> [[b, a] for [a, b] in f]
[[4, 1], [5, 2], [6, 3]]