Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove elements in a list after a specific element in Python list (slice not applicable)

Tags:

python

list

I have a python list shown below. I want to remove all the elements after a specific character ''

Note1: The number of elements before '' can vary. I am developing a generic code.

Note2: There can be multiple '' I want to remove after the first ''

Note3: Slice is not applicable because it supports only integers

Can someone please help me with this?

Thank you very much.

['iter,objective,inf_pr,inf_du,lg(mu),||d||,lg(rg),alpha_du,alpha_pr,ls',
 '0,8.5770822e+000,1.35e-002,1.73e+001,-1.0,0.00e+000,-,0.00e+000,0.00e+000,0',
 '1,8.3762931e+000,1.29e-002,1.13e+001,-1.0,9.25e+000,-,9.86e-001,4.62e-002f,2',
 '5,8.0000031e+000,8.86e-010,1.45e-008,-5.7,1.88e-004,-,1.00e+000,1.00e+000h,1',
 '6,7.9999994e+000,1.28e-013,2.18e-012,-8.6,2.31e-006,-,1.00e+000,1.00e+000h,1',
 '',
 'Number,of,Iterations....:,6',
 '',
 '(scaled),(unscaled)',
 'Objective...............:,7.9999994450134029e+000,7.9999994450134029e+000',
 'Dual,infeasibility......:,2.1781026770818554e-012,2.1781026770818554e-012',
 'Constraint,violation....:,1.0658141036401503e-013,1.2789769243681803e-013',
 'Complementarity.........:,2.5067022522763431e-009,2.5067022522763431e-009',
 'Overall,NLP,error.......:,2.5067022522763431e-009,2.5067022522763431e-009',
 '',
 '',
like image 900
Rua Goa Avatar asked Nov 30 '25 06:11

Rua Goa


1 Answers

list = ['a', 'b', 'c', '', 'd', 'e']
list = list[:list.index('')]
#list is now ['a', 'b', 'c']

Explanation: list.index('') finds the first instance of '' in the list. list[:x] gives the first x elements of the list. This code will throw an exception if '' is not in the list.

like image 65
ThisIsAQuestion Avatar answered Dec 01 '25 18:12

ThisIsAQuestion