我有一个主数据源,它由一个列表列表和一个元组字典组成,这些元组字典索引了我从主数据源中需要的信息。
我想使用元组字典为主数据源中的每个条目编制索引,并使用此信息创建一个新列表。
我创建了下面的代码,但错误显示“类型错误:列表索引必须是整数,而不是生成器”
我已经搜索了如何遍历列表列表中的每个列表,但没有找到解决方案。
欢迎提出任何建议。
#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])]) 你使用一个元组作为MyDat。但是 integer 是必需的。
