Having some difficulty trying to take a 2d list with 7 columns and 10 rows, and append all rows from only columns 4,5 and 6 (or 3,4,5 from index 0) to a new list. The original list is actually a csv and is much, much longer but I've just put part of it in the function for troubleshooting purposes.
What I have so far is...
def coords():
# just an example of first couple lines...
bigList = [['File','FZone','Type','ID','Lat','Lon','Ref','RVec']
['20120505','Cons','mit','3_10','-21.77','119.11','mon_grs','14.3']
newList=[]
for row in bigList[1:]: # skip the header
newList.append(row[3])
return newList # return newList to main so it can be sent to other functions
This code gives me a new list with 'ID' only but I also want 'Lat' and 'Lon'.
The new list should look like...['3_10', '-21.77','119.11']['4_10','-21.10'...]
I tried re-writing newList.append(row[3,4,5])...and of course that doesn't work but not sure how to go about it.
row[3] refers to the fourth element. You seem to want the fourth through sixth elements, so slice it:
row[3:6]
You could also do this all with a list comprehension:
newList = [row[3:6] for row in myList[1:]]
Related
Objective: I have a list of 200 elements(urls) and I would like to check if each one is in a specific column of the Dataframe. If it is, I would like to remove the element from the list.
Problem: I am trying a similar solution by adding to a new list the ones that are not there but it adds all of them.
pruned = []
for element in list1:
if element not in transfer_history['Link']:
pruned.append(element)
I have also tried the solution I asked for without success. I think it's a simple thing but I can't find the key.
for element in list1:
if element in transfer_history['Link']:
list1.remove(element)
When you use in with a pandas series, you are searching the index, not the values. To get around this, convert the column to a list using transfer_history['Link'].tolist(), or better, convert it to a set.
links = set(transfer_history["Link"])
A good way to filter the list is like this:
pruned = [element for element in list1 if element not in links]
Don't remove elements from the list while iterating over it, which may have unexpected results.
Remember, your syntax for transfer_history['Link'] is the entire column itself. You need to call each item in the column using another array transfer_history['Link'][x]. Use a for loop to iterate through each item in the column.
Or a much easier way is to just check if the item is in a list made of the entire column with a one liner:
pruned = []
for element in list1:
if element not in [link for link in transfer_history['Link']]:
pruned.append(element)
If the order of the urls doesn't matter, this can be simplified a lot using sets:
list1 = list(set(list1) - set(transfer_history['Link']))
I have a list of lists say, for example:
directions = [[-1,0,1],[1,0,4],[1,1,2][-1,1,2]]
now, in any of the nested lists the index [2] is of no importance in the test.
I want to try to find if the first two values in any of the nested lists match the inverse of any other, To clarify further by inverse I mean the negative value In python code. preferable with only one line but if that not possible than a work around to get the same effect.
and if is condition is true and the third values of the two nested lists should be added together and stored in the second original list in the check function and the second list which was the inverse one should be deleted.
So
if nested list's first 2 values == -another nested list's first 2 values
add their third values together
list delete(inverse list)
I hope this makes a little more sense.
I have tried this below but I still cant get it to skip the 3 value or index 2
listNum = 0
while len(directions) > listNum:
if (-directions[listNum][0], -directions[listNum][1], anything(Idk)) in directions:
index = index(-directions[listNum][0], -directions[listNum][1], anything(Idk))
directions[listNum][2] += directions[index][2]
directions.del(index)
But I don't know what to put where I put anything(Idk)
I have a list of lists containing information about smartphone applications. Each list (within the list) contains the same type of information, in the same order.
[id, name, ..., ].
The list of lists looks like this: [[id1, name1,...], [id2, name2, ...]]
I want to access the 10th index in each list and check its value.
I tried this, but it does not work. I imagined this would iterate over every list, except the first which is a header, and would select the 10th item in each list.
for c_rating in apps_data[1:][10]:
print(c_rating)
Instead, it prints out every item within the 10th list.
The given solution is:
for row in apps_data[1:]:
c_rating = row[10]
print(c_rating)
I understand why this code works. It breaks the process into two steps. I don't understand why the first code does not work. Any help would be appreciated.
That's due to the python expression evaluation order.
apps_data[1:][10] is evaluated in this order:
apps_data[1:] -> this gives a list of the inner lists with all but the first inner list. Let's call this inner_lists
inner_lists[10] -> this gives you the 10th element from that list of lists. Which gives you one of those inner lists.
So you end up with a select + select
What you want is a iterate + select. You can do it like this:
[print(x[10]) for x in apps_data]
This goes through all the inner_lists, selecting the 10th element from each and prints it.
The following problem I have, might be very trivial for a more advanced python programmer, but I -- as a python beginner -- can't figure out the problem.
I just want to delete a row from a 2D-list, if it matches a certain condition --- in my case, if the row contains a certain character. I wanted to do it in a more functional, python way, rather than looping over all list items. Therefore, my attempt was
alist = [[1,2],[3,4]]
map(lambda ele : (if 2 in ele: tmp3.remove(ele)), alist)
which should just delete the first row, because it contains a "2". But I just get an error "invalid syntax" and I don't know why!
(I also came across some solution which uses dataframes from the pandas package, but as I'm learning python, I want to avoid pandas at this stage ;) )
Thanks in advance!
You can't use an if statement in a lambda. You could use the more clearer list comprehension:
alist = [row for row in alist if 2 not in row]
This also has the advantage of iterating through the list once, as opposed to using map and list.remove, although you get a new list.
If you are trying to remove elements from a list, you need filter instead of map which is often used for transformation and doesn't change the length of the list:
alist = [[1,2],[3,4]]
filter(lambda ele : 2 not in ele, alist)
# [[3, 4]]
All right, so I have a code where I need to print a game board with 5x5 squares. All the squares is in squareList, which is a list (oh you don't say). A square is based on an object with a variable number that is the value I want to print. How can I do this?
EDIT: The reason to why I want to do this is because I want to start on a new line every five squares so that I get a board, not a line, with values.
The python slice / array operator supports an optional step as the third value. squareList[start:end:step]:
for o in squareList[::5]:
print(o.number)
Use 5 as the step value to get every fifth entry in the list.
Why not make list for each row in the square, and then put those rows into a list?
squareList = [rowList1, rowList2, rowList3, rowlist4, rowList5]
This way you can manipulate a column as you loop through the rows.
for row in SquareList:
doSomething(row[4])
You can also extract a column using a list comprehension.
colList1 = [row[0] for row in squareList]
I would agree that you might want to consider other more convenient structures for your data, as suggested by CCKx.
Here are two approaches
Assuming:
squareList = [0,0,1,0,0,
1,2,0,0,1,
0,0,0,1,2,
2,2,0,0,0,
1,0,0,0,1]
Then you can do this:
for index, value in enumerate(squareList):
print(value, end='')
if (index % 5) == 4:
print()
(I'm assuming Python 3.)
That will literally do what you asked for in the way that you asked for it. index will count up through each element of your list, and the % or "modulo" operator will get you the remainder when you divide by 5, allowing you to take some action every 5 times round the loop.
Or you can use slicing:
for row in range(5):
for cell in squareList[row*5:row*5+5]:
print(cell, end='')
print()
See also:
What is the most "pythonic" way to iterate over a list in chunks?