0

From the given two lists:

fruits = ['apple', 'banana', 'kiwi', 'mango', 'avocardo']
quantities = [5, 8, 7, 15, 22]

How to get the result below?

fruits_having_less_than_10quantities = ['apple', 'banana', 'kiwi']

I am looking for implementing it using dictionary.

2
  • 2
    That doesn't make sense. It's not a dictionary-type problem. Commented Mar 6, 2014 at 2:12
  • 2
    What do you get when you cross Ricky Ricardo with an avocado? Avocardo! (This was a light-hearted attempt to humorously point out your spelling mistake) Commented Mar 6, 2014 at 2:13

4 Answers 4

4
fruits = ['apple', 'banana', 'kiwi', 'mango', 'avocardo']
quantities = [5, 8, 7, 15, 22]

fhlt = [fruit for fruit,num in zip(fruits,quantities) if num < 10]
    # => ['apple', 'banana', 'kiwi']

Edit or as a dictionary:

fruitnum = {fruit:num for fruit,num in zip(fruits, quantities) if num < 10}
    # => {'apple': 5, 'banana': 8, 'kiwi': 7}

Edit2: if you are concerned about extra temporary lists, in Python 2, you can

from itertools import izip
fhlt = [fruit for fruit,num in izip(fruits,quantities) if num < 10]

instead; in Python 3 this is not necessary, as zip is already a generator.

Sign up to request clarification or add additional context in comments.

Comments

2

I really think you should use a dictionary {fruit: quantity} but here you are

>>> fruits = ['apple', 'banana', 'kiwi', 'mango', 'avocardo']
>>> quantities = [5, 8, 7, 15, 22]
>>> fruits_having_less_than_10quantities = [ elem[0] for elem in zip(fruits, quantities) if elem[1] < 10 ]
>>> fruits_having_less_than_10quantities
['apple', 'banana', 'kiwi']

Comments

1

Another option:

[fruits[i] for i in xrange(0, len(fruits)) if quantities[i] < 10]

The above has the advantage that it doesn't create any extra temporary lists. As others have pointed out, this is not a dictionary-type problem, but still…

Comments

0

I think we can trying using bisect:

from bisect import bisect

def disect(fr, qr, n, side=None):
    ind = bisect(zip(*sorted(zip(fr, qr), key=lambda tup: tup[1]))[1], n)
    if side == 'left':
        return fr[:ind]
    elif side == 'right':
        return fr[ind:]
    raise Exception("which side you want")

fruits = ['apple', 'banana', 'kiwi', 'mango', 'avocardo']
quantities = [5, 8, 7, 15, 22]

print disect(fruits, quantities, 10, 'left')
print disect(fruits, quantities, 10, 'right')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.