Holsterbau
Holsterbau

Reputation: 87

Accessing lists a referenced element is inside of

Let's say I got a list of lists, like so:

x = [
["spam", "bacon", "eggs", "tomatoes"]
]

Then I make a reference to an element inside of the first element (list) in the list.

y = x[0][1]  # which should be "bacon"

Now I wish to access, having only reference y at disposal, other elements that are with "bacon", and maybe even lists next to the list "bacon" is part of. Here is more specifically what I would need that for:

y = x[0][1]
z = x[0][0]

class Thing:
    def __init__(self, stuff)
        self.stuff = stuff
    def checkstuff()
        # if stuff from different instance of class is member of the same list, things happen

spam = Thing(stuff=y)
bacon = Thing(stuff=z)

Upvotes: 0

Views: 78

Answers (1)

pjmaracs
pjmaracs

Reputation: 118

Question is a bit vague, would add comment normally but rep too low. Here's my guess at what you want...

x = [
["spam", "bacon", "eggs", "tomatoes"],
["spam", "bacon", "eggs", "tomatoes"],
["spam", "notthisone", "eggs", "tomatoes"],
["spam", "bacon", "eggs", "tomatoes"],
["spam", "orthisone", "eggs", "tomatoes"]
]

y = x[0][1]
print(y)
indicesContaining = []
for i in range(len(x)):
    for string in x[i]:
        if string == y and i not in indicesContaining:
            indicesContaining.append(i)
print (indicesContaining)

This gets you the indices of the outer list in which the element y is contained. Edit: answer is now outdated, question changed

Upvotes: 1

Related Questions