我是Python的初学者。目前,我正在制作汽车阅读工具,目的只是为了提高一些编程技能。一切正常。
当我从汽车的控制模块获得故障代码时,我得到了P代码。喜欢:
P2348和P21E2(随机P码)
我可以检索这些P代码,但是我想向它们添加更多信息。 P代码可以链接到故障描述:
P2348-检测到失火(随机)
我希望我的程序提供扩展信息,而不仅仅是P代码。有成千上万个P代码,我都带有说明。但是一千条If语句将是不好的编码。我可以在文本文件中查找P代码并从中获取完整的字符串,但这并不是一个选择(除非可以在代码本身中或使用可执行文件进行编译)。
执行此操作的一种好方法是什么?在上编程课之前,我曾遇到过此问题。那时,我使用了IF语句(大约20条),我讨厌它。
答案 0 :(得分:2)
使用字典:
<script>
var data = [
{
"BP": "Title",
"Attr": ["Attr 1", "Attr2"],
"Tables": ["Fact", "Fact", "Fact", "Fact", "Fact"],
"Vendor": ["Vendor1"],
"BO": ["Vxy", "XYZ"]
},
{
"BP": "KYB",
"Attr": ["Attr 1", "Attr2"],
"Tables": ["Data Not Persisted"],
"Vendor": ["LX"],
"BO": ["JXA", "HJZ"]
}];
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
$('#search').keyup(function() {
$('#result').html('');
$('#state').val('');
var searchField = $('#search').val();
// i makes the search case insensitive
var expression = new RegExp(searchField, "i");
console.log(expression)
$.each(data, function(key, value) {
if (value.BP.search(expression) != -1 || value.Tables.search(expression) != -1) {
$('#result').append('<li class="list-group-item link-class">' + value.Vendor + '|<span class="text-muted">' + value.BP + '|<span class="text-muted">' + value.Tables + '</li>');
//console.log(value.Tables);
}
});
});
$('#result').on('click', 'li', function() {
var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');
});
});
</script>
然后您可以在dict中查找键,而无需使用code_descr = {
'P2348': 'Misfire detected',
'P8866': 'Engine is on fire',
'P7777': 'Tires missing',
}
:
if
您可以编写代码以某种格式(csv,json等)读取数据库并生成字典,因此您可以在程序外部获得描述