📌  相关文章
📜  Python|从给定的列表中获取正元素

📅  最后修改于: 2022-05-13 01:55:15.316000             🧑  作者: Mango

Python|从给定的列表中获取正元素

给定一个列表列表,任务是只从给定列表中获取正元素。以下是解决上述问题的一些方法。

方法#1:使用迭代

# Python code to get positive 
# element from list of list
  
# List Initialisation
Input = [[10, -11, 222], [42, -222, -412, 99, -87]]
Output = []
  
# Using iteration
for elem in Input:
    temp = []
    for x in elem:
        if x>0:
            temp.append(x)
    Output.append(temp)
    
# printing output
print("Initial List is :", Input)
print("Modified list is :", Output)
输出:
Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]]
Modified list is : [[10, 222], [42, 99]]


方法#2:使用地图和列表理解

# Python code to get positive element 
# from list of list
  
# List Initialisation
Input = [[10, -11, 222], [42, -222, -412, 99, -87]]
  
# Using list comprehension and map
temp = map(lambda elem: filter(lambda a: a>0, elem), Input)
Output = [[a for a in elem if a>0] for elem in temp]
  
# printing output
print("Initial List is :", Input)
print("Modified list is :", Output)
输出:
Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]]
Modified list is : [[10, 222], [42, 99]]


方法#3:使用列表理解

# Python code to get positive element 
# from list of list
  
# List Initialisation
Input = [[10, -11, 222], [42, -222, -412, 99, -87]]
  
# Using list comprehension
Output = [ [b for b in a if b>0] for a in Input]
  
# printing output
print("Initial List is :", Input)
print("Modified list is :", Output)
输出:
Initial List is : [[10, -11, 222], [42, -222, -412, 99, -87]]
Modified list is : [[10, 222], [42, 99]]