我有一个主数据源,包括一个列表列表和一个元组字典,用于索引我从主数据源中需要的信息。
我希望使用元组字典对主数据源中的每个条目进行索引,并使用这些信息创建一个新列表。
我在下面创建了代码,但错误是"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']]发布于 2016-11-11 14:52:59
for i in tupDict:
tmp = MyDat # temporary variable to store data by current index
for x in tupDict[i]: # iterate over indexes in tuple
tmp = tmp[ x ] # set tmp to data by index
newList.append( tmp ) #we finish iterating over index, now tmp hold value that we need另外,我要提到的是,newList中元素的顺序可能会有所不同,因为dict不保存元素的顺序。
如果您希望newList中的元素与您在代码中定义的顺序相同,那么您应该使用来自collections模块的OrderedDict。
https://stackoverflow.com/questions/40550277
复制相似问题