How Can I Find The Locations Of An Item In A Python List Of Lists?
Solution 1:
If you want something that will both
- find duplicates and
- handle nested lists (lists of lists of lists of ...)
you can do something like the following:
defget_positions(xs, item):
ifisinstance(xs, list):
for i, it inenumerate(xs):
for pos in get_positions(it, item):
yield (i,) + pos
elif xs == item:
yield ()
Testing this:
>>>xs = [['1', '2', '4', '6'],... ['7', '0', '1', '4'],... [ [ '0', '1', '1'], ['1']]... ]>>>printlist(get_positions(xs, '1'))
[(0, 0), (1, 2), (2, 0, 1), (2, 0, 2), (2, 1, 0)]
Solution 2:
It looks likes you want, for a list of sublists and a given item, to return a list of pairs where each pair is (the index of the sublist, the index of the item within the sublist). You can do that using list comprehensions and Python's built in enumerate()
function:
defgetPosition(list, item):
return [(i, sublist.index(item)) for i, sublist inenumerate(list)]
Edit: See @scribble's answer above/below.
Solution 3:
defgetPosition(list, item):
return [(i, sublist.index(item)) for i, sublist inenumerate(list)
if item in sublist]
Solution 4:
defget_positions(xs, target):
return [(i,e.index(target)) for i,e inenumerate(xs)]
That's a good starting point. Presumably you have some sort of class such as
classSomeClass:def__init__(self):
self.xs = [['1','2','4','6'], ['7','0','1','4']]
defget_positions(self, target):
return [(i,e.index(target)) for i,e in enumerate(self.xs)]
which in this case would let you say
model = SomeClass()
model.get_position(1) # returns [(0,0), (1,2)]
Note that in both cases you'll get an exception if your target isn't in every one of your sublists. The question does not specify whether this is the desired behavior.
Solution 5:
If you don't want a exception if the item is not in the list try this. Also as a generator because they are cool and versatile.
xs = [['1', '2', '4', '6'], ['7', '0', '1', '4']]
defget_positions(xs, item):
for i, xt inenumerate( xs ):
try: # trying beats checkingyield (i, xt.index(item))
except ValueError:
passprintlist(get_positions(xs, '1'))
printlist(get_positions(xs, '6'))
# Edit for fun: The one-line version, without try:
get_positions2 = lambda xs,item: ((i,xt.index(item)) for i, xt inenumerate(xs) if item in xt)
printlist(get_positions2(xs, '1'))
printlist(get_positions2(xs, '6'))
Post a Comment for "How Can I Find The Locations Of An Item In A Python List Of Lists?"