[英]List comprehension on two lists
Let's say I have two equal-length lists, list1
and list2
, both consisting of a bunch of numbers. 假设我有两个等长列表, list1
和list2
,都由一堆数字组成。 I want to remove all the elements of list1
that don't meet a certain criterion. 我想删除不符合特定条件的所有list1
元素。 Simple enough. 很简单。 How would I also remove the corresponding elements from list2
though? 但是,如何从list2
删除相应的元素呢? If I remove, say, the 5th element of list1
, I would also like to remove the 5th element of list2
. 如果我删除了list1
的第5个元素,那么我也想删除list2
的第5个元素。 Example of what I'm trying to do below: 下面我尝试做的例子:
list1 = [i for i in list1 if i >= 1]
list2 = list2 #but with the corresponding values of list1 removed from list2 as well
I could come up with, say, 我可以想出,
list2_temp = []
for j in range(len(list1)):
if list1[j] >= 1:
list2_temp.extend(list2[j])
list1 = [i for i in list1 if i >= 1]
but I am looking for a more "Pythonic" way to do it, specifically if there is any way I can use list comprehensions on list2
as well as list1
. 但我正在寻找一种更“ Pythonic”的方法来实现此目的,特别是如果有任何方法可以在list2
和list1
上使用列表list2
。 Any ideas/suggestions? 有什么想法/建议吗?
合并,过滤,拆分:
list1[:], list2[:] = zip(*((x, y) for (x, y) in zip(list1, list2) if predicate(x)))
I think that maybe the problem is that you have 2 parallel lists rather than a single list that holds items which have the all the data for each element. 我认为问题可能在于您有2个并行列表,而不是一个单独的列表,其中包含具有每个元素的所有数据的项目。
Think of the data as a spreadsheet -- Currently you have 2 columns and you want to filter the rows by the values in one column. 可以将数据视为电子表格-当前您有2列,并且要按一列中的值过滤行。 Rather than modeling the data as a bunch of columns, it's better to model it as a list of rows. 与其将数据建模为一堆列,不如将其建模为行列表。
To fix the problem now you can zip the lists together, filter them and then unzip at the end: 现在要解决此问题,您可以将列表压缩在一起,过滤它们,然后在末尾解压缩:
items = [(i, j) for i, j in zip(list1, list2) if i >= 1]
tuple1, tuple2 = zip(*items)
but I still recommend considering storing the data in a different way... 但我仍然建议考虑以其他方式存储数据...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.