[英]Find index of element in sublist that is same across all the sublists in a nested list
[英]Try to find a sublist that doesnt occur in the range of ANY of the sublists in another list
enhancerlist=[[5,8],[10,11]]
TFlist=[[6,7],[24,56]]
我有两个列表列表。 我正在尝试隔离我的“TFlist”中不适合增强列表的任何子列表范围的子列表(按范围:TFlist 子列表范围适合增强列表子列表范围内)。 因此,例如,TFlist[1] 不会出现在增强列表中的任何子列表的范围内(而 TFlist [6,7] 适合 [5,8] 的范围内),所以我希望它是 output:
TF_notinrange=[24,56]
像这样的嵌套 for 循环的问题:
while TFlist:
TF=TFlist.pop()
for j in enhancerlist:
if ((TF[0]>= j[0]) and (TF[1]<= j[1])):
continue
else:
TF_notinrange.append(TF)
是我得到这个作为 output: [[24, 56], [3, 4]]
if 语句一次检查 enhancerlist 中的一个子列表,append TF 也会如此,即使稍后有一个子列表在其范围内。
我能以某种方式对条件进行 while 循环吗? 虽然看起来我仍然有嵌套循环错误地附加东西的问题?
选择
使用列表理解:
TF_notinrange = [tf for tf in TFlist
if not any(istart <= tf[0] <= tf[1] <= iend
for istart, iend in enhancerlist)]
print(TF_notinrange)
>>> TF_notinrange
解释
获取不包含在任何增强列表范围内的 TFlist 范围
附加限制
通过以下任一方式创建多行条件来添加额外的约束:
TF_notinrange = [tf for tf in TFlist
if TFlist[0]==enhancerlist[0] and \
not any(istart <= tf[0] <= tf[1] <= iend)
for istart, iend in enhancerlist]
tF_notinrange = [tf for tf in TFlist
if (TFlist[0]==enhancerlist[0] and
not any(istart <= tf[0] <= tf[1] <= iend)
for istart, iend in enhancerlist)]
For 循环与列表理解
正如 doejohn 所评论的那样,列表理解是针对简单代码的。 对于复杂的约束,出于可读性考虑,最好使用 for 循环。
tF_notinrange = []
for tf in TFlist:
if (TFlist[0]==enhancerlist[0] and # place multile constraints
not any(istart <= tf[0] <= tf[1] <= iend)):
tF_notinrange.append(tf)
您可以将链式比较与不太常见for-else
块一起使用,其中else
子句仅在for
循环未过早中断时才会触发以实现此目的:
non_overlapping = []
for tf_a, tf_b in TFlist:
for enhancer_a, enhancer_b in enhancerlist:
if enhancer_a <= tf_a < tf_b <= enhancer_b:
break
else:
non_overlapping.append([tf_a, tf_b])
请注意,这假定所有对都已排序,并且没有任何对包含长度为零的范围(例如, (2, 2)
)。
编辑:OP,你在测试的某个地方犯了一些错误。
In [1]: def non_overlapping(TFlist, enhancerlist):
...: result = []
...:
...: for tf_a, tf_b in TFlist:
...: for enhancer_a, enhancer_b in enhancerlist:
...: if enhancer_a <= tf_a < tf_b <= enhancer_b:
...: break
...: else:
...: result.append([tf_a, tf_b])
...:
...: return result
...:
In [2]: enhancerlist=[[5,8],[10,15]]
...: TFlist=[[6,7],[11, 14], [54,56], [55,56]]
In [3]: non_overlapping(TFlist, enhancerlist)
Out[3]: [[54, 56], [55, 56]] # [11, 14] is not present, as you claim
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.