删除仅包含空的订阅者仅在特定位置的订订者
考虑列表:
list_1 = [
[
[1, 2, 3], [], [3, 4, 5], [], [4, 5, 6], [7, 8, 9], [9, 1, 0]
],
[
[0, 1, 2], [9, 0, 1], [], [0, 1, 3], [1, 1, 1], [9, 5, 6], [3, 6, 7]
],
[
[1, 2, 4], [4, 5, 6], [], [1, 0, 1], [0, 1, 1], [3, 9, 7], []
],
[
[1, 3, 4], [], [3, 5, 6], [], [], [], [0, 7, 0]
]
]
如果其中包含第1,第三或第7位的空列表,我想删除该行。
例如,必须删除第二行和第三行的上方。 我尝试了一下:
list_2 = [sublist for sublist in list_1 if all(x for x in sublist)]
如何称呼索引1、3、7?
Consider the list:
list_1 = [
[
[1, 2, 3], [], [3, 4, 5], [], [4, 5, 6], [7, 8, 9], [9, 1, 0]
],
[
[0, 1, 2], [9, 0, 1], [], [0, 1, 3], [1, 1, 1], [9, 5, 6], [3, 6, 7]
],
[
[1, 2, 4], [4, 5, 6], [], [1, 0, 1], [0, 1, 1], [3, 9, 7], []
],
[
[1, 3, 4], [], [3, 5, 6], [], [], [], [0, 7, 0]
]
]
I want to remove a row if it contains empty list either at 1st , 3rd or 7th position.
For example above the 2nd and 3rd rows must be removed.
I tried this:
list_2 = [sublist for sublist in list_1 if all(x for x in sublist)]
How I call the index 1, 3, 7 in this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
filter
a href =“ https://docs.python.org/3/library/operator.html” rel =“ nofollow noreferrer”>operator.itemgetter.itemgetter
。
nb。由于您的列表有7个元素,而Python索引从0开始,我以为您是指元素0、2、6
输出:
Using
filter
and list slicing withoperator.itemgetter
.NB. as your lists have 7 elements and python indexing starts at 0, I assumed you mean elements 0, 2, 6
output:
这应该起作用。
方法1
list_2
的元素('row's)上的外循环循环,而内循环,对于list_2
循环的某些固定元素list_2
的该元素的元素,直到它在所需位置找到一个空列表,然后从内部循环中折断,以便我们移至list_2 。休息之前,
list_2
索引存储在delete_indices
list中。循环完成后,我们使用delete_indices
来确定要保留哪个行。输出
方法2 遵循与方法1相似的逻辑,并且比方法1快(见下文)。
比较
从效率方面,您应该更喜欢 @Mozway的方式。
This should work.
Method 1
The outer loop loops over the elements ('row's) of
list_2
whereas the inner loop, for some fixed element oflist_2
loops over the elements of that element oflist_2
until it finds an empty list in the required position and then breaks from the inner loop so that we move onto another element ('row') oflist_2
. Before the break, thelist_2
index that is in place is stored in thedelete_indices
list. After the loop is done, we usedelete_indices
to decide which rows to keep.Output
Method 2 follows a similar logic to method 1 and is faster than method 1 (see below).
Comparison
Efficiency-wise, you should prefer @mozway's way.