拥有list
个dict
个对象,其中50%将拥有密钥name
,50%将拥有密钥full_name
,我希望按字母顺序排序在任何一个键上。
某种类似的功能:
if 'name' in a:
a_name = a['name']
elif 'full_name' in a:
a_name = a['full_name']
# repeat with a b in the compare, sort based on value
这里有更有效的方式吗?
答案 0 :(得分:1)
我认为它应该有效:
sorts = sorted(data, key= lambda x: x.get('name') or x.get('full_name'))
答案 1 :(得分:0)
连接两个字符串,用空字符串替换缺少的字符串:
class PhoneResource(ModelResource):
class Meta:
queryset = Phone.objects.all()
allowed_methods = ['get']
resource_name = 'phone'
class CustomerResource(ModelResource):
phone = fields.ManyToManyField(PhoneResource, "phone")
class Meta:
queryset = Customer.objects.all()
allowed_methods = ['get', 'patch', 'put']
resource_name = 'customer'
authentication = Authentication()
authorization = Authorization()
def prepend_urls(self):
return [
url(r'^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/phone%s$' %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('get_customer_phone'), name='customer_phone'),
]
def customer_phone(self, request, **kwargs):
# My Question is what goes in this function
# I want to get only the phones for the given customer, and exclude other phones that does not belong to them
答案 2 :(得分:-1)
您是否尝试过基于lambda的功能方法:
testList = sorted(testList, key=lambda name: a_name['name'] if 'name' in a_name else a_name['full_name'])