Click here to Skip to main content
15,896,314 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to remove zero values from a list in python. I've tried some codes but it still shows the zero values. Here is my list.

In [128]: allData
Out[128]: 
[['Brand', 'Type', 'Release'],
 ['Nissan', 'seDan', '2010'],
 ['Hyundae', 'suv', '2011'],
 ['BMW', 'seDan', '2012'],
 ['Hyun dae', 'seDan', '2012'],
 ['BMW', 'suv', '2012'],
 ['BMW', 'suv', '0']]


The below code what I've tried is a part of the full script.
Please help me to solve the issue.
Thank you.

What I have tried:

import csv
import os

fileToRead = "est1.csv"

f = open(fileToRead, 'r')
reader = csv.reader(f)
allData = list(reader)
totalCols = len(attributes)
totalRows = len(allData)
f.close()

# Add a '0' for each empty cell
for j in range(0,totalCols):
	for i in range(0,totalRows):
		if 0 == len(allData[i][j]):
			allData[i][j] = "0"
# Remove zero value
for j in range(0,totalCols):
	for i in range(0,totalRows):
		list(filter(lambda a: a !="0", allData[i]))
Posted
Updated 19-Aug-20 0:43am

You start by replacing 0 by "0" - which is not necessary. Secondly your filter call does not save the resulting list; try:
Python
allData[i] = list(filter(lambda a: a !=0, allData[i]))
 
Share this answer
 
Comments
Member 14738587 9-Feb-20 22:17pm    
Thank you so much for your help. It works! Thank you.
Hello,
I just saw the solutions posted.

Python is known for the ability to compress number of lines of code and it is certainly the way you write code in C/C++ or java.

You can use the concept of list comprehension - a unique feature of python and very popular among modern age python programmers.

Let's take an example:

say I define a list

>>> a = [1,2,0,3,0,5,6,7,0,10]


Now to remove all '0' in the list, just use "list comprehension" i.e.

>>> [x for x in a if x !=0]
[1, 2, 3, 5, 6, 7, 10]
>>>


Cool right !!


Cheers,
Joydeep
 
Share this answer
 
v2
Hi, my solution remove everything you don't like in a list as follows, enjoy:

s1 = [2, 5.6, 0,"u", 78, 0, -3.6, 96, "t"]

s2 = [i for i in s1 if type(i) != str]
s1 = [i for i in s2 if type(i) != float]
s2 = [[i for i in s1 if i != 0]]

print(s2, end= " ")
print()
 
Share this answer
 
a=[0,1,2,3,0,0,0,0,5,6,7,8,0,0]
ll=len(a)
i=0
while i<ll:
if="" a[i]="=0:
" del="" a[i]
="" print(a)
="" ll="ll-1
" i="0
" else:
="" print(a)<="" code="">
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900