-2

I have a list with [vehicle name, number]

a=[["car","A1"],["car","A2"],["truck","A1"]]

I need a function such that if i specify

car it should return "A2" the last number in that vehicle name. If i specify bike it should return "A0"

I tried writing something but keep getting an error list index out of range

EDIT:

here's the full list format

["vehicle","color","vehicle_num","status(True/False)","code"]

vehicle and color is given and last vehicle_num should be found, if vehicle,color doesn't exist return "A0"

The number system starts from "A1",.........."An"

n varies according to the vehicle,color

list is already sorted

Noel DSouza
  • 71
  • 1
  • 9

3 Answers3

2

Use a dictionary

You can take advantage of the fact dict assigns values in order and list is an ordered collection. So, for duplicate keys within your list of lists, the last mapping persists.

a = [["car","A1"], ["car","A2"], ["truck","A1"]]

d = dict(a)

print(d['car'])    # A2
print(d['truck'])  # A1

Revert to list if you need to afterwards (which you don't, as you can write to csv from a dictionary).

res = list(map(list, d.items()))

print(res)

[['car', 'A2'], ['truck', 'A1']]
jpp
  • 159,742
  • 34
  • 281
  • 339
0

You can use something like this:

def search(l, word):
    res = "A0"
    for i in l:
        if i[0] == word:
            res
    return res

You can then optimise it by saving "An" as Tupel of A with an integer n.

-1
a = {'car':['A1', 'A2'], 'bike':['A0'], 'truck': ['A1']}

def return_last(vehicle):
  return a[vehicle][-1]

return_last('car')
Surya Tej
  • 1,342
  • 2
  • 15
  • 25