'Delete specific lists inside a list
import xlsxwriter
import xlrd
excel = xlrd.open_workbook('C:/Users/sel/Desktop/5/Book1.xlsx')
sheet = excel.sheet_by_index(0)
all_data = []
for row_index in range(sheet.nrows):
row = []
for col_index in range(sheet.ncols):
valor = sheet.cell(row_index,col_index).value
if valor == '':
for crange in sheet.merged_cells:
rlo, rhi, clo, chi = crange
if rlo <= row_index and row_index < rhi and clo <= col_index and col_index < chi:
valor = sheet.cell(rlo, clo).value
break
row.append(valor)
all_data.append(row)
The data in excel or all_data is [[2.0, 0.0, 30.0], [2.0, 1.0, 20.0], [2.0, 5.0, 52.0], [8.0, 2.0, 58.0], [8.0, 3.0, 67.0], [8.0, 4.0, 85.0], [15.0, 7.0, 75.0], [15.0, 8.0, 24.0], [15.0, 6.0, 16.0], [5.0, 7.0, 46.0], [5.0, 5.0, 75.0], [5.0, 7.0, 85.0]]
I want to remove the lists in which the first number is less than 8.
l=[]
for i in range(sheet.nrows):
if all_data[i][0]<8:
l.append(i)
l here is [0, 1, 2, 9, 10, 11] which specifies the position of lists to be removed.
How do I remove those lists all at once?
I tried the code below, but it did not work
for i in l:
del(all_data[i])
print(all_data)
Solution 1:[1]
In python, it is almost always easier to keep what you want than to remove what you do not want:
all_data = [d for d in all_data if d[0] >= 8]
#[[8.0, 2.0, 58.0], [8.0, 3.0, 67.0], ..., [15.0, 6.0, 16.0]]
There is no need for a list of indexes.
Solution 2:[2]
Simply don't append valor to the row when its first element is less than 8. This way you don't have to check all_data for the values later. No need to write the other two for loops or any list comprehension
import xlsxwriter
import xlrd
excel = xlrd.open_workbook('C:/Users/sel/Desktop/5/Book1.xlsx')
sheet = excel.sheet_by_index(0)
all_data = []
for row_index in range(sheet.nrows):
row = []
for col_index in range(sheet.ncols):
valor = sheet.cell(row_index,col_index).value
if valor == '':
for crange in sheet.merged_cells:
rlo, rhi, clo, chi = crange
if rlo <= row_index and row_index < rhi and clo <= col_index and col_index < chi:
valor = sheet.cell(rlo, clo).value
break
if valor[0] >= 8:
row.append(valor)
all_data.append(row)
Solution 3:[3]
this is one way of doing it.
all_data = [lst for index, lst in enumerate(all_data) if index not in l]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DYZ |
| Solution 2 | Atul |
| Solution 3 |
