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
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.
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']
why not use a basic list slice? something like:
list = list[3:] #everything from the 3 position to the end
You want del for that
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
Related
I am trying to remove the last item of a list/array even if there are duplicate items
EG
list = ["h","e","l","l","o"," ","t","h","e","r,"e"]
It would remove the final "e" but not the second and ninth "e"
I have already tried
finalSentence.remove([finalSentence[len(finalSentence)-1]])
However this removes a random letter, I know this is because it is removing a letter rather than item number and python does not know which one to choose so it is a random one that is removed. But I do not know another way to get this to work
.remove removes the first occurrence of an item. You could do something like
del my_list[len(my_list) - 1]
Or simply:
del my_list[-1]
Or, probably the most idiomatic:
my_list.pop()
Note, the above methods work in (amortized) constant time, and they modify my_list in-place.
Do not use list as a variable name, as it will probably conflict with the built-in type. But try this:
mylist = mylist[:-1]
That uses a slice from the beginning of the list up to but not including the last element. If the list is empty, there is no apparent change. If you want an error to be raised, you should use one of the methods of #juanpa.arrivillaga.
I am currently writing a small bit of logic for my HTML page. My aim is to create variables (lists) within an iteration (using the iteration to create the names of said lists as the amount of them will be unknown to the program). I am currently creating the lists like this:
maps={}
currentMap = elements[0].process
counter=0
for i in elements:
if(counter==0):
maps["mapsEle{0}".format(counter)]=[]
counter+=1
if(i.process!=currentMap):
currentMap = i.process
maps["mapEle{0}".format(counter)]=[]
counter+=1
else:
print("No change found, keeping heading the same.")
However as you can probably tell, this does not create a list but a string. I try to print the variables (e.g. mapsEle0) and it returns the variable name (e.g. print(mapsEle0) returns "mapsEle0") this too me is suprising as I would have thought if the dictionary is saving it as a string it would print "[]".
So I am looking for a way to create lists within the dictionary in that iteration I am using there, basically want to just reformat my declaration. Cheers in advance everyone :)
Edit:
As requested here is the code where I attempt to append. Please note I want to append 'i' into the lists and no the dictionary.
for i in maps:
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
#i.append(x)
The syntax of your print statement is wrong, if you want to access the contents of the dictionary, you need to use different notation.
Instead of print('mapsEle0') you need to do print(maps['mapsEle0']).
Update:
Unfortunately your description of what you want and your code are a bit conflicting, so if you can, please try to explain some more what this code is supposed to do.
for i in maps.iterkeys():
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
maps[i].append(x)
This will iterate over all keys of maps ('mapsEle0'...'mapsEleN') and add x to the contained list if the elif condition is fulfilled.
You're printing the string by doing print('mapsEle0').
To print the dict, you must print(maps) - 'll print the whole dictionary, OR, to print a specific key/element print(maps['mapsEle0'])
To elaborate it further here's a interpreter session:
>>> maps = {}
>>> counter = 0
>>> maps["mapsEle{0}".format(counter)]=[]
>>> maps
{'mapsEle0': []}
>>>
>>> print(maps)
{'mapsEle0': []}
>>>
>>> print(maps['mapsEle0'])
[]
>>>
For the append part:
>>> maps['mapsEle1'].append('hello')
>>> print(maps['mapsEle1'])
['hello']
Edit 2: Your statement is still not clear
As requested here is the code where I attempt to append. Please note I
want to append 'i' into the lists and no the dictionary.
I think sobek has got it right - you want to append x to the mapsEle0, mapsEle1 lists, which are keys in maps dictionary.
for i in maps.iterkeys():
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
maps[i].append(x)
I am trying to print a list of lists in python like so:
for location in latLongList:
print ' '.join(map(str, location))
This prints out:
40.0349216312 -75.1900864349 Paved 4 0.156150432289
39.9531308619 -75.1629612614 Paved 3 0.170932927052
39.9610355788 -75.1725011285 Paved 0.17296824247
39.9788367755 -75.2123945669 Paved 0.196740550111
39.9467944475 -75.2092212039 Paved 33 0.210834020854
39.94626513 -75.2089212417 Paved 5 0.210899309368
39.9373184367 -75.2341880089 Grass 0.236747322815
39.9413269464 -75.2383849209 0.238056333485
This works fine but I wanted to exclude the last number in each line (which is the last number in each sublist). I also wanted to be able to allow the user to specify the number of lines to be printed. They input that number through the command line and it is stored in a variable called sizeOfList. Would there be an easy way to do this in python? Any help would be greatly appreciated!
You could use the built-in function enumerate to get the index of each location in latLongList, and then print only locations whose index is less than the number desired by the user (sizeOfList). Then, in order to exclude the last item in each sublist (each location), you could take a slice of the sublist up to, but not including, the last item (which is at index -1).
for i, location in enumerate(latLongList):
if i < sizeOfList:
print ' '.join(map(str, location[:-1]))
#Hackaholic introduced an improvement to this method, which makes the code more concise and potentially much faster (due to iteration over fewer locations):
for location in latLongList[:sizeOfList]:
print ' '.join(map(str, location[:-1]))
Here, only the items up to the number desired by the user (sizeOfList) are taken from latLongList. There is no longer a need for enumerate.
You could do something like this:
# this import needs to be first
from __future__ import print_function
for location in latLongList[:sizeOfList]:
print(*location[:-1])
The __future__ import makes print a function, so you can do print(*foo). That's like print(foo[0], foo[1], ...).
First, to print everything but the last element, you slice the list to include everything but its last element: location[:-1]. (Slicing is explained in the tutorial in Using Python as a Calculator; for full details see Sequence Types in the library reference.)
Then, to stop after a certain number of lines, you slice the list of lines: latLongList[:sizeOfList].
So:
for location in latLongList[:sizeOfList]:
print ' '.join(map(str, location[:-1]))
If the list weren't actually a list, but an iterator (or if you were writing generic code that needed to work with both), or if you were worried about the memory waste in making a copy of part of the list (say because you want the first 200 million lines), you could use islice, which solves both of those problems:
from itertools import islice
for location in islice(latLongList, sizeOfList):
print ' '.join(map(str, location[:-1]))
Better to try like this:
for location in latLongList[:sizeOfList]:
print ' '.join(map(str, location[:-1]))
This should solve both problems:
print '\n'.join('{} {} {}'.format(*location) for location in latLongList[:sizeOfList])
This solution is pretty Pythonic. Using str.format() eliminates the need to convert everything to strings by using map(str, ) (str.format() does this automatically for you). Additionally, there is no need to slice the sublist for each location to eliminate the last element, as str.join() ignores the rest of the list automatically. Lastly, it reduces the number of calls to print from sizeOfList times to once. And the str.join() operation is fast because it is joining an iterator instead of a list.
Enjoy!
Is there any "pythonic way" to tell python to loop in a string (or list) starting from the last item and ending with the first one?
For example the word Hans i want python to read or sort it as snaH
Next, how can i tell pyhon the following: now from the string you resulted , search for 'a' find it ok , if you find 'n' follows 'a' , put '.' after 'n' and then print the original order of letters
The clearest and most pythonic way to do this is to used the reversed() builtin.
wrong_way = [1, 2, 3, 4]
for item in reversed(wrong_way):
print(item)
Which gives:
4
3
2
1
This is the best solution as not only will it generate a reversed iterator naturally, but it can also call the dedicated __reversed__() method if it exists, allowing for a more efficient reversal in some objects.
You can use wrong_way[::-1] to reverse a list, but this is a lot less readable in code, and potentially less efficient. It does, however, show the power of list slicing.
Note that reversed() provide iterators, so if you want to do this with a string, you will need to convert your result back to a string, which is fortunately easy, as you just do:
"".join(iterator)
e.g:
"".join(reversed(word))
The str.join() method takes an iterator and joins every element into a string, using the calling string as the separator, so here we use the empty string to place them back-to-back.
How about this?
>>> s = "Hans"
>>> for c in s[::-1]:
print c
s
n
a
H
Alternatively, if you want a new string that's the reverse of the first, try this:
>>> "".join(reversed("Hans"))
'snaH'
Sure, just use list_name[::-1]. e.g.
>>> l = ['one', 'two', 'three']
>>> for i in l[::-1]:
... print i
...
three
two
one
I have a list and I want to remove from it the items that don't appear in another list. I've tried the following:
for w in common:
for i in range(1,n):
if not w in words[i]:
common.remove(w)
However, this fails to remove some of the items. Adding print statements for w in common:
for i in range(1,n):
print w
if not w in words[i]:
print w
common.remove(w)results in some w never being printed. Any ideas as to what's happening? I assume the answer's simple and I just don't have adequate Python knowledge, but I'm completely out of ideas.
I think you can simplify your statement with something like this:
filtered = filter(lambda x: x in words, common)
That's checking each element in common for it's presence in words and removing based on it. You may need to try x not in words depending on what you're desired result is, but I think that should come close.
I wanted to add one other approach, that might also come close, though I would need to see examples of your initial lists to test it fully.
filtered = [x for x in common if x in words]
-- EDITED -- I had the syntax in the list comprehension backwards, but caught it after I saw the comment. Thanks!
You can't delete items from the list you're iterating over. Try iterating over a copy of the list instead.
for w in common[:]:
for i in range(1,n):
if not w in words[i]:
common.remove(w)
From the Python docs:
It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy.
You are modifying the list while trying to iterate through it.
You could modify the first line of the code to iterate through a copy of the list (using common[:]).
If you delete (say) item 5, then the old item 6 will now be item 5. So if you think to move to item 6 you will skip it.
Is it possible to iterate backwards over that list? Then index-changes happen in parts you already processed.