我有一个主数据源,由列表列表和元组字典组成,用于从主数据源中索引我需要的信息。
我想使用元组字典来索引主数据源中的每个条目,并使用此信息创建一个新列表。
我创建了下面的代码,但错误显示“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/