use*_*344 0 python list python-3.x
Suppose I have a list of lists.
L = [[1,2,3], ['a',2,True],[1,44,33,12.1,90,2]]
Run Code Online (Sandbox Code Playgroud)
I want to be able to remove all instances of a specific element from each of the sublists in the list L.
So for instance I might want to remove the number 2 so this would produce
L = [[1,3], ['a',True],[1,44,33,12.1,90]]
Run Code Online (Sandbox Code Playgroud)
I tried to use this function + code:
def remove_values_from_list(the_list, val):
return [value for value in the_list if value != val]
for i in L:
i = remove_values_from_list(i, '2')
Run Code Online (Sandbox Code Playgroud)
However the output still gives L in its original form and doesn't remove the 2.
i是未连接到的变量L。从中分配了一个值L,然后将其重新分配给其他值;这一点都不会影响L。
一种非破坏性的方法(例如,保存L,为结果创建一个新列表):
newL = [[value for value in the_list if value != val] for the_list in L]
Run Code Online (Sandbox Code Playgroud)
破坏性的方式(即改变L自身):
for the_list in L:
while value in the_list:
the_list.remove(value)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |