说我有一个字典列表。
listOfDict = [{"name": "Joel","Age": "10","Grade": "A"},{"name": "Adam","Age": "11","Grade": "B"},{"name": "Rachel","Age": "10","Grade": "B"}]
我想获取一个年龄为10岁的名字的列表。因此输出看起来像这样。
listOfNames = ["Joel", "Rachel"]
有没有一种方法可以不使用for循环或if条件。我尝试使用Lambda函数,但无济于事。
答案 0 :(得分:4)
有没有一种方法,而无需使用for循环或if条件
使用循环。在 some 级别这是不可避免的。使用列表理解:
res = [d['name'] for d in listOfDict if d['Age'] == '10']
答案 1 :(得分:1)
这有效。
使用lambda:
result = list(map(lambda x: x['name'] if x['Age'] == "10" else None, listOfDict ))
result = [x for x in result if x is not None]
print(result)
答案 2 :(得分:1)
没有- @mandatory_signatures.each do |mandatory_signature|
.form-group.row.mt-4
.col-sm-5
%label Choose #{mandatory_signature.signature_title}
.centered-vertical
= select_tag '', options_from_collection_for_select(find_users_with_certificate_for(mandatory_signature), :id, :full_name), { include_blank: "Select User", class: 'form-control select2 find-user-certificate', style: 'width: 100%;', data: { mandatory: mandatory_signature.id } }
.col-sm-5
%label Choose Certificate
.centered-vertical
= select_tag nil, "", { include_blank: "Select Certificate", class: "form-control select2 certificate-list js-#{ mandatory_signature.id }", style: 'width: 100%;' }
$('.find-user-certificate').change(function() {
let user_id = $(this).val();
let mandatory_id = $(this).data('mandatory')
getUserCertificates(user_id, mandatory_id);
});
function getUserCertificates(userId, mandatoryId) {
let hostname = window.location.origin;
$.ajax({
url: hostname + '/users/' + userId + '/certificates',
dataType: 'json',
method: 'get',
success: function(data) {
options = '';
data.forEach(function(object) {
options += `<option value=${object.id}>${object.name}</option>`;
});
$('.certificate-list.js-' + mandatoryId).empty();
$('.certificate-list.js-' + mandatoryId).append(options);
}
});
}
使用pandas.DataFrame
的循环或for
条件:
if
输出
import pandas as pd
df=pd.DataFrame.from_dict(listOfDict)
result=df[df['Age']=='10']['name'].tolist()
答案 3 :(得分:1)
有一种方法可以使用lambda函数以及map
和filter
来获得所需的结果,而无需使用for
循环或{{1 }}条件,但代码将有点难以理解:
if
结果:
listOfDict = [{"name": "Joel","Age": "10","Grade": "A"},{"name": "Adam","Age": "11","Grade": "B"},{"name": "Rachel","Age": "10","Grade": "B"}]
listOfNames = list(map(lambda elem: elem['name'], list(filter(lambda elem: elem['Age']=="10",listOfDict))))
print(listOfNames)