由于缺少matlab,我试图将matlab代码转换为python。如果您能告诉我以下函数的python等价物,我将不胜感激:
letter2number_map('A') = 1;
number2letter_map(1) = 'A';
str2num()
strcmp()
trace()
eye()
getenv('STRING')
[MI_true, ~, ~] = function() What does ~ mean?
mslice
ones()
非常感谢您的帮助。
答案 0 :(得分:2)
从字母转换为数字:ord("a") = 97
从数字转换为字母:chr(97) = 'a'
(您可以减去96以获得您正在寻找小写的结果,或64减去大写。)
将字符串解析为int:int("523") = 523
比较字符串(区分大小写):"Hello"=="Hello" = True
不区分大小写:"Hello".lower() == "hElLo".lower() = True
ones()
:[1]*ARRAY_SIZE
身份矩阵:[[int(x==y) for x in range(5)] for y in range(5)]
要制作二维数组,您需要使用numpy。
编辑:
或者,您可以像这样制作一个5x5二维数组:[[1 for x in range(5)] for y in range(5)]
答案 1 :(得分:2)
我实际上并不知道matlab,但我可以回答其中一些(假设您已将numpy导入为np):
letter2number_map('A') = 1; -> equivalent to a dictionary: {'A':1}
number2letter_map(1) = 'A'; -> equivalent to a dictionary: {1:'A'}
str2num() -> maybe float(), although a look at the docs makes
it look more like eval -- Yuck.
(ast.literal_eval might be closest)
strcmp() -> I assume a simple string comparison works here.
e.g. strcmp(a,b) -> a == b
trace() -> np.trace() #sum of the diagonal
eye() -> np.eye() #identity matrix (all zeros, but 1's on diagonal)
getenv('STRING') -> os.environ['STRING'] (with os imported of course)
[MI_true, ~, ~] = function() -> Probably: MI_true,_,_ = function()
although the underscores could be any
variable name you wanted.
(Thanks Amro for providing this one)
mslice -> ??? (can't even find documentation for that one)
ones() -> np.ones() #matrix/array of all 1's