如何根据特定条件 select 列表的一部分
How to select part of a list based on certain conditions
我想执行以下操作:
L = [(1,2),(3,4),(5,6)]
new_list = list( element in L for i,j in L if i >1 and j >4)
new_list
的结果将是 [(5,6)]
我知道如何为一维列表执行此操作,例如:
L1 = [1,2,3,4]
new_L1 = list( i for i in L1 if i>1 )
但我不知道如何对 python 中的多维列表执行类似操作。
您可以正常迭代元组:
new_l = [tup for tup in L if tup[0] > 1 and tup[1] > 4]
您可以在主循环中将嵌套元组解压到您想要的变量中:
[(i, j) for i, j in L if i > 1 and j > 4]
请注意,您必须 'reconstruct' 左侧表达式中的原始元组。
或者,使用索引寻址元素:
[elem for elem in L if elem[0] > 1 and elem[1] > 4]
请注意,我在这里使用了 list comprehension(您在 list()
函数中使用了 生成器表达式 ,得到了类似的结果高效的方式)。
我想执行以下操作:
L = [(1,2),(3,4),(5,6)]
new_list = list( element in L for i,j in L if i >1 and j >4)
new_list
的结果将是 [(5,6)]
我知道如何为一维列表执行此操作,例如:
L1 = [1,2,3,4]
new_L1 = list( i for i in L1 if i>1 )
但我不知道如何对 python 中的多维列表执行类似操作。
您可以正常迭代元组:
new_l = [tup for tup in L if tup[0] > 1 and tup[1] > 4]
您可以在主循环中将嵌套元组解压到您想要的变量中:
[(i, j) for i, j in L if i > 1 and j > 4]
请注意,您必须 'reconstruct' 左侧表达式中的原始元组。
或者,使用索引寻址元素:
[elem for elem in L if elem[0] > 1 and elem[1] > 4]
请注意,我在这里使用了 list comprehension(您在 list()
函数中使用了 生成器表达式 ,得到了类似的结果高效的方式)。