如何从一组结果中列出清单?

时间:2019-06-11 16:54:40

标签: python python-3.x list

所以在这里我在python中定义了一个函数,该函数告诉给定的数字是偶数还是奇数。

现在我想创建一个列表,将结果中的数字作为要素,这怎么可能?

def even_till_n(number):
     for in range(number+1): 
        if  (i%2 == 0):
             print(i)

2 个答案:

答案 0 :(得分:1)

您需要创建一个列表变量并将值附加到该变量。然后让您的函数返回该列表:

def even_till_n(number):
     result = list()
     for i in range(number+1): 
        if  (i%2 == 0):
             result.append(i)
     return result

# usage ...

test = even_till_n(10)
print(test)

# [0, 2, 4, 6, 8, 10]

答案 1 :(得分:0)

使用列表理解。

let data = [{ "campaignId": 111, "campaignCategory": "Diabetes", "result": [{ "campaignType": 1, "name": "tes1" }, { "campaignType": 1, "name": "test22" }, { "campaignType": 3, "name": "test33" } ] }, { "campaignId": 222, "campaignCategory": "Orthopedic", "result": [{ "campaignType": 1, "name": "Orthopedic" }] }, { "campaignId": 333, "campaignCategory": "Cardiology", "result": [{ "campaignType": 3, "name": "Cardiology" }, { "campaignType": 1, "name": "Cardiology 123" } ] } ]

let result = data.reduce((r,{result,...rest}) => {
  result.forEach(x => x.campaignType === 3 ? r.push({...rest, result:[x]}) : null)
  return r
}, [])

console.log(result)