Finding the first index in a list greater than a particular value

Michael Selik michael.selik at gmail.com
Sun Aug 14 23:01:22 EDT 2016


On Sun, Aug 14, 2016 at 2:21 PM Atri Mahapatra <atri.mahapatra at gmail.com>
wrote:
> I have a list of dictionaries which look like this:
> [{'Width': 100, 'Length': 20.0, 'Object': 'Object1'}, {'Width': 12.0,
> 'Length': 40.0, 'Object': 'Object2'}...... so on till 10]
>> I would like to find the first index in the list of dictionaries whose
> length is greater than a particular value
>> f=lambda seq, m: [ii for ii in range(0, len(seq)) if seq[ii]['Length'] >
> m][0] and it throws an error
>> can anyone suggest a way to do it?
>
There's no need to play code golf (squishing your thoughts into one line).
 def index_of_first_record_of_minimum_size(records, m):
 'records is an iterable of dictionaries'
 for i, dictionary in enumerate(list_of_dicts):
 if dictionary['Length'] > m:
 return i
 raise ValueError('no record found with "Length" greater than %r' %
(m,))
If you have trouble coming up with a good name for a function, that
suggests you are either doing too much or too little with that function. If
you want the same task outside of a function, change the return to a break.
 if not records:
 raise ValueError('no records found')
 for index, d in enumerate(records):
 if d['Length'] > m:
 break # `index` is now the index of the first record of minimum
length
 else:
 raise ValueError('no record found with "Length" greater than %r' %
(m,))


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /