首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用元组中的索引组合列表中的信息的Python

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

Stack Overflow用户
提问于 2016-11-11 14:38:22
回答 2查看 51关注 0票数 2

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

我希望使用元组字典对主数据源中的每个条目进行索引,并使用这些信息创建一个新列表。

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

我已经搜索过如何在列表列表中迭代每个列表,但没有找到解决方案。

欢迎任何建议。

代码语言:javascript
运行
复制
#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中选择的列的新列表。例如:

代码语言:javascript
运行
复制
Stage1: (0,2) 

会创建这个列表

代码语言:javascript
运行
复制
[['round', 'square', 'oblong', 'circle', 'round'], ['rough','rough','smooth','rough','smooth']]
EN

Stack Overflow用户

发布于 2016-11-11 14:52:59

代码语言:javascript
运行
复制
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

票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40550277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档