raylee2015 发表于3年前

• 发表于 3年前
• 阅读 2
• 收藏 0
• 评论 0

``````>>> aList=[1,2,3,4,5]
>>> def test(aList):
res=[]
for x in range(len(aList)):
if aList[x]%2==0:
res.append(aList[x])
return res

>>> test(aList)
[2, 4]
>>>``````

2.第二种我们采用filter

``````>>> list(filter(lambda x:x%2==0,[1,2,3,4,5]))
[2, 4]
>>>``````

3.第三种使用列表解析实现

``````>>> [x for x in [1,2,3,4,5] if x %2==0]
[2, 4]
>>>``````

``````>>> aList=[1,2,3,4,5]
>>> def test(aList):
res=[]
for x in range(len(aList)):
if aList[x]%2==0:
aList[x]+=1
res.append(aList[x])
return res

>>> test(aList)
[3, 5]``````

2.第二种我们采用filter、map和lambda表达式联合实现

``````>>> aList=[1,2,3,4,5]
>>> list(map(lambda x :x+1,filter(lambda x:x%2==0,aList)))
[3, 5]
>>>``````

3.第三种使用列表解析实现

>>> [x+1 for x in [1,2,3,4,5] if x %2==0]
[3, 5]
>>>

for循环嵌套在列表解析里面

``````>>> [x+y for x in range(4) for y in range(2)]
[0, 1, 1, 2, 2, 3, 3, 4]
>>> [(x,y) for x in range(4) for y in range(2)]
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)]
>>>``````

``````>>> def test():
res=[]
for x in range(4):
for y in range(2):
res.append(x+y)
return res

>>> test()
[0, 1, 1, 2, 2, 3, 3, 4]
>>>

>>> def test():
res=[]
for x in range(4):
for y in range(2):
res.append((x,y))
return res

>>> test()
[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1), (3, 0), (3, 1)]
>>>``````

``````>>> [(x,y) for x in range(4) if x%2==0 for y in range(5) if y%2!=0]
[(0, 1), (0, 3), (2, 1), (2, 3)]
>>>``````

``````>>> def test():
res=[]
for x in range(4):
if x%2==0:
for y in range(5):
if y%2!=0:
res.append((x,y))
return res

>>> test()
[(0, 1), (0, 3), (2, 1), (2, 3)]
>>>``````

------------------------------------------------------------------

×