Python中的简单列表操作

时间:2014-03-06 02:07:35

标签: python

从给定的两个列表中:

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

如何获得以下结果?

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

我正在寻找使用字典实现它。

4 个答案:

答案 0 :(得分: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']

修改或作为字典:

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

Edit2:如果你担心额外的临时列表,在Python 2中,你可以

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

代替;在Python 3中,这不是必需的,因为zip已经是一个生成器。

答案 1 :(得分:2)

我真的认为你应该使用字典{fruit:quantity},但在这里你是

>>> 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']

答案 2 :(得分:1)

另一种选择:

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

以上优点是它不会创建任何额外的临时列表。正如其他人所指出的,这不是字典型问题,但仍然......

答案 3 :(得分:0)

我认为我们可以尝试使用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')