python - 访问列表中的引用元素
问题描述
假设我有一个列表列表,如下所示:
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)
解决方案
问题有点模糊,通常会添加评论但代表太低。这是我对你想要什么的猜测......
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 的外部列表的索引。编辑:答案现已过时,问题已更改
推荐阅读
- python - Azure 容器实例部署失败
- java - 使用 @ConfigurationProperties 解析的属性的要求
- excel - 在 VBA 函数中使用 Round 函数
- openmodelica - OmSimulator 与 Python(如何在 OmSimulator Python 上禁用输出文件更新)
- pug - 创建一个带有跨度的 li 和文本
- javascript - 如何从 forEach 调用一些全局变量
- corda - NodeRPCConnection.java 而不是 NodeRPCConnection.kt
- python - 字符串格式 - 法国口音
- javascript - 在 Flow 中声明一个通用形状的对象
- python - python 2.7 搜索和替换文件中的多行