Python 使用元组中的索引组合列表列表中的信息

标签 python

我有一个主数据源,由列表列表和元组字典组成,用于从主数据源中索引我需要的信息。

我想使用元组字典来索引主数据源中的每个条目,并使用此信息创建一个新列表。

我创建了下面的代码,但错误显示“TypeError:列表索引必须是整数,而不是生成器”

我已经搜索了如何迭代列表列表中的每个列表,但尚未找到解决方案。

欢迎任何建议。

#List of data
MyDat = [['round', 'square', 'oblong', 'circle', 'round'],['orange','orange','purple','green','yellow'],    ['rough','rough','smooth','rough','smooth']]

#Tuples required to create new list of variable combinations 
tupDict = {"stage1": (0,2), "stage2": (1,)}

newList = []

for i in tupDict:
        newList.append(MyDat[(x for x in tupDict[i])])

print(newList)

新列表应创建 MyDat 中所选列的新列表。例如:

Stage1: (0,2) 

将创建此列表

[['round', 'square', 'oblong', 'circle', 'round'], ['rough','rough','smooth','rough','smooth']]

最佳答案

如果我理解正确,你可以尝试这样:

MyDat = [['round', 'square', 'oblong', 'circle', 'round'],['orange','orange','purple','green','yellow'],    ['rough','rough','smooth','rough','smooth']]

#Tuples required to create new list of variable combinations 
tupDict = {"stage1": (0,2), "stage2": (1,)}

newList = []

for i in tupDict:
    newList.extend([MyDat[x] for x in tupDict[i]])

print(newList)

我刚刚更改了这一行:

newList.append(MyDat[(x for x in tupDict[i])])

对此:

newList.extend([MyDat[x] for x in tupDict[i]])

这一行:newList.append(MyDat[(x for x in tupDict[i])])您正在使用tuple作为 MyDat 的索引。但是integer是需要的。

关于Python 使用元组中的索引组合列表列表中的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40550277/

相关文章:

python - 如何使用管理员在 Python 中运行 cmd 命令

python按键简单的游戏

Python Pandas : find max values in a cell

python - 文件 "pylab.py"的用途是什么

python - 箱线图之外的点是否为异常值?

python - Scrapy:没有标题的 CSV 输出

python - Gitlab CI - Django 功能测试 - split

python - 检查两个数组是否可以在 python 中广播

python - uWSGI Empire 模式无法在 Virtualenv 之外工作

python - Scala 中的 python @classmethod 或 @staticmethod 等价于什么?