简体   繁体   中英

Python: removing specific lines from an object

I have a bit of a weird question here.

I am using iperf to test performance between a device and a server. I get the results of this test over SSH, which I then want to parse into values using a parser that has already been made. However, there are several lines at the top of the results (which I read into an object of lines) that I don't want to go into the parser. I know exactly how many lines I need to remove from the top each time though. Is there any way to drop specific entries out of a list? Something like this in psuedo-python

print list
["line1","line2","line3","line4"]
list = list.drop([0 - 1])
print list
["line3","line4"]

If anyone knows anything I could use I would really appreciate you helping me out. The only thing I can think of is writing a loop to iterate through and make a new list only putting in what I need. Anyway, thanlks!

Michael

This is what the slice operator is for:

>>> before = [1,2,3,4]
>>> after = before[2:]
>>> print after
[3, 4]

In this instance, before[2:] says 'give me the elements of the list before , starting at element 2 and all the way until the end.'

(also -- don't use reserved words like list or dict as variable names -- doing that can lead to confusing bugs)

You can use slices for that:

>>> l = ["line1","line2","line3","line4"] # don't use "list" as variable name, it's a built-in.
>>> print l[2:] # to discard items up to some point, specify a starting index and no stop point.
['line3', 'line4']
>>> print l[:1] + l[3:] # to drop items "in the middle", join two slices.
['line1', 'line4']

Slices:

l = ["line1","line2","line3","line4"]
print l[2:] # print from 2nd element (including) onwards 
["line3","line4"]

Slices syntax is [from(included):to(excluded):step] . Each part is optional. So you can write [:] to get the whole list (or any iterable for that matter -- string and tuple as an example from the built-ins). You can also use negative indexes, so [:-2] means from beginning to the second last element. You can also step backwards, [::-1] means get all, but in reversed order.

Also, don't use list as a variable name. It overrides the built-in list class.

why not use a basic list slice? something like:

list = list[3:] #everything from the 3 position to the end

你想要那个

del list[:2]

You can use "del" statment to remove specific entries :

del(list[0]) # remove entry 0
del(list[0:2]) # remove entries 0 and 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM