我有以下MATLAB代码,我想用Python复制。
MATLAB代码为string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
string[] dateStrings = {"5/1/2009 6:32 PM", "05/01/2009 6:32:05 PM",
"5/1/2009 6:32:00", "05/01/2009 06:32",
"05/01/2009 06:32:00 PM", "05/01/2009 06:32:00"};
DateTime dateValue;
foreach (string dateString in dateStrings)
{
if (DateTime.TryParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None,
out dateValue))
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
else
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
时创建逻辑数组,然后使用该逻辑数组从xDiff == 2
数组中提取相应的值,以创建结果数组tDiff
。
MATLAB代码:
tTacho
答案 0 :(得分:2)
你可以用NumPy做boolean indexing 例如:
import numpy as np
x_diff = np.array([0, 2, 2, 0, 0, 2])
t_diff = np.array([0, 1, 2, 3, 4, 5])
print(t_diff[x_diff == 2])
给出:
array([1, 2, 5])
如果您不想使用NumPy,则可以将list comprehensions与zip一起使用:
x_diff = [0, 2, 2, 0, 0, 2]
t_diff = [0, 1, 2, 3, 4, 5]
print([t for t, x in zip(t_diff, x_diff) if x == 2])
给出:
[1, 2, 5]
答案 1 :(得分:0)
您也可以使用列表索引。
tDiff=[1,2,4,5,6,6,7]
xDiff=[2,3,2,2,2,2,2]
for x in range(0,len(xDiff)):
if xDiff[x]==2:
print tDiff[x]
如果这有帮助。