Sook Yee Lim Sook Yee Lim - 3 years ago 193
Python Question

How to append a list into another list based on the items in a list?

I got this list:

verticeToCompare=['Q']


and I got these two lists:

a=[[0, 1, 2, 1, 9, 'a'], [1, 0, 0, 6, 0, 'c'], [2, 0, 0, 15, 2, 'g'], [1, 6, 15, 0, 7, 'w'], [9, 0, 2, 7, 0, 'Q']]
b=[[0, 19, 1, 0, 12, 0, 'a'], [19, 0, 2, 0, 0, 0, 'c'], [1, 2, 0, 0, 2, 0, 'w'], [0, 0, 0, 0, 3, 5, 'Q'], [12, 0, 2, 3, 0, 2, 'front'], [0, 0, 0, 5, 2, 0, 'Z']]


I want to extract the list with the end item 'Q' from list a and b and append to the list extracted from a to a new listToCompareOne=[] and list extracted from b to
a new listToCompareTwo=[].I tried with this code but it returns an empty list?

for item in verticeToCompare:
for itemTwo in firstMatrixOriginal:
if item==itemTwo[-1]:
listToCompare.append(itemTwo)
for item in verticeToCompare:
for itemTwo in secondMatrixOriginal:
if item==itemTwo[-1]:
listToCompareTwo.append(itemTwo)

Answer Source

You can use a list comprehension with a nested loop, it'll return elements from a, followed by those from b.

>>> [y for x in verticeToCompare for y in a + b if y[-1] == x]
[[9, 0, 2, 7, 0, 'Q'], [0, 0, 0, 0, 3, 5, 'Q']]

However, if your ending strings are unique, you should consider using a dictionary of ending strings : values to store your data instead, so you'd then be able to access values associated with ending strings in constant time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download