我試圖使用lambda的效仿以下Python代碼:什麼是等效的lambda?
checkName = lambda list, func: func([re.search(x, name, re.I) for x in list])
if checkName(["(pdtv|hdtv|dsr|tvrip).(xvid|x264)"], all) and not checkName(["(720|1080)[pi]"], all):
return "SDTV"
elif checkName(["720p", "hdtv", "x264"], all) or checkName(["hr.ws.pdtv.x264"], any):
return "HDTV"
else:
return Quality.UNKNOWN
我已經創造了長格式下面的C#代碼,但我相信它可以使用lambda表達式縮短:
if (CheckName(new List<string> { "(pdtv|hdtv|dsr|tvrip).(xvid|x264)" }, fileName, true) == true &
CheckName(new List<string> { "(720|1080)[pi]" }, fileName, true) == false)
{
Quality = Global.EpisodeQuality.SdTv;
}
private bool CheckName(List<string> evals, string name, bool all)
{
if (all == true)
{
foreach (string eval in evals)
{
Regex regex = new Regex(eval, RegexOptions.IgnoreCase);
if (regex.Match(name).Success == false)
{
return false;
}
}
return true;
}
else
// any
{
foreach (string eval in evals)
{
Regex regex = new Regex(eval, RegexOptions.IgnoreCase);
if (regex.Match(name).Success == true)
{
return true;
}
}
return false;
}
}
任何幫助將不勝感激提高我的理解!我相信有一個更簡單/更簡單的方法!
所以經過一些更多的上場我把它簡化爲:
private static bool CheckName(List<string> evals,
string name,
bool all)
{
if (all == true)
{
return evals.All(n =>
{
return Regex.IsMatch(name, n, RegexOptions.IgnoreCase);
});
}
else
// any
{
return evals.Any(n =>
{
return Regex.IsMatch(name, n, RegexOptions.IgnoreCase);
});
}
}
但一定要使用Func鍵像Python代碼當量?
請記住,如果'evals'是空'All'將返回true。 – 2013-03-22 11:54:32