访问列表中引用的元素位于其中

时间:2019-07-18 16:54:55

标签: python arrays python-3.x

假设我有一个列表列表,像这样:

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

然后,我引用列表中第一个元素(列表)内部的元素。

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

现在,我希望仅使用参考y来访问与"bacon"一起使用的其他元素,甚至可能访问列表"bacon"旁边的列表。更具体地说,这是我需要的:

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)

1 个答案:

答案 0 :(得分:1)

问题有点含糊,可以正常添加评论,但代表太低。这是我对您想要的东西的猜测...

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)

这将为您获取包含元素y的外部列表的索引。 编辑:答案现在已经过时,问题已更改