[英]How to remove item equal to some value from list of lists?
I need to remove all item[0]
if a
is == '1'
: 如果
a
== '1'
我需要删除所有item[0]
:
a = [['1','2','3'], ['2','4','9']]
for item in a:
if item[0] == '1':
del item
您可以按以下方式使用列表理解
a = [i for i in a if i[0] != '1']
Do not change length of list while iterating over it. 在迭代列表时不要更改列表的长度。 make new list instead.
改为创建新列表。
b = [i for i in a if i[0] != '1']
Use filter
: 使用
filter
:
new_a = list(filter(lambda item: item[0] != '1', a))
The list is just so its compatible regardless of your python version ( filter
returns lazy sequence in python3). 无论您使用什么python版本,列表都是这样兼容的(
filter
返回python3中的惰性序列)。
A List Comprehension is the best way to solve this problem but if you want to use a for loop here's some Python code for that: 列表理解是解决此问题的最佳方法,但是如果您要使用for循环,则可以使用以下Python代码:
a = [[1,2,3], [2,1,9], [1,6,9], [5,6,7]]
# Code
def removeOneList(a):
for item in a:
if item[0] == 1:
del item[:]
return a
print(removeOneList(a))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.