什么相当于这个列表理解?

时间:2017-10-17 20:49:10

标签: python python-3.x list-comprehension

列表理解:

$ echo p̄ | grep . -o | wc -l
2

列表理解的结果:

def getBiggerNumber(input_number, generated_number):    
         return [x for x in generated_number if x > input_number]

我试图获得与上述相同的结果。

Generated Numbers : [7, 9, 14, 18, 27, 41, 44, 46, 54, 55, 57, 57, 57, 64, 65, 81, 82, 82, 83, 95]
Enter a number 1-100: 44
Your number: 44
Numbers greater than 44 : [46, 54, 55, 57, 57, 57, 64, 65, 81, 82, 82, 83, 95]

我从中得到的结果是:

for x in generated_number:
     if x > input_number:
          print(x)

2 个答案:

答案 0 :(得分:2)

如您所见,一步一步

def doThing(input_number,generated_number):
  return [x for x in generated_number if x > input_number]

print(doThing(10,[100,10,20,40]))

def doSameThing(input_number,generated_number):
  res = []
  for x in generated_number:
    if x > 10:
      res.append(x)

  return res

print(doSameThing(10,[100,10,20,40]))

你正在使用> 10制作过滤器,列表理解只是它的语法糖

答案 1 :(得分:1)

列表推导的等价物

def getBiggerNumber(input_number, generated_number):
    return [x for x in generated_number if x > input_number]

print(getBiggerNumber(44, [20, 66, 100]))


def same(xnum, ylist, lst=[]):
    for x in ylist:
        if x > xnum:
            lst.append(x)
    return lst

print(same(44, [20, 66, 100]))
  

输出:

[66, 100]
[66, 100]
>>>