首页 > 解决方案 > 访问列表中的引用元素

问题描述

假设我有一个列表列表,如下所示:

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)

标签: pythonarrayspython-3.x

解决方案


问题有点模糊,通常会添加评论但代表太低。这是我对你想要什么的猜测......

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 的外部列表的索引。编辑:答案现已过时,问题已更改


推荐阅读