remove all elements in a list with a particular value

Steven Howe howe.steven at gmail.com
Fri May 18 20:20:32 EDT 2007


Steven Howe wrote:
> MRAB wrote:
>> On May 16, 4:21 pm, Lisa <lisa.engb... at gmail.com> <mailto:lisa.engb... at gmail.com> wrote:
>>   
>> I am reading in data from a text file.  I want to enter each value on
>> the line into a list and retain the order of the elements.  The number
>> of elements and spacing between them varies, but a typical line looks
>> like:
>>
>> '   SRCPARAM   1 6.35e-07 15.00  340.00   1.10      3.0   '
>>   
> Using builtin functions:
>
>     ax = '   SRCPARAM   1 6.35e-07 15.00  340.00   1.10      3.0   '
>     >>> ax.replace('  ','')  # replace all double spaces with nothing
>     ' SRCPARAM 1 6.35e-07 15.00340.00 1.103.0 '
>     >>> ax.replace('  ','').strip() # strip leading/trailing white spaces
>     'SRCPARAM 1 6.35e-07 15.00340.00 1.103.0'
>     >>> ax.replace('  ','').strip().split(' ') # split string into a
>     list, using remaining white space as key
>     ['SRCPARAM', '1', '6.35e-07', '15.00340.00', '1.103.0']
>
>     def getElements( str ):
>         return str.replace( '  ', '' ).strip().split(' ')
>
>
> sph
>
Made a mistake in the above code. Works well so long as there are no 
double spaces in the initial string.
Try 2:
def compact( y ):
    if y.find('  ') == -1:
         return y
    else:
        y = y.replace( '  ', ' ' )
        return compact( y )

 >>> ax = '   acicd  1.345   aex      a;dae    '
 >>> print compact( ax )
 acicd 1.345 aex a;dae
 >>> print compact( ax ).strip().split()
['acicd', '1.345', 'aex', 'a;dae']

sph

> -- 
> HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0
>   


-- 
HEX: 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0




More information about the Python-list mailing list