2017-03-08 112 views
-1

因此,在构造元组列表时,某些元组内的顺序似乎混杂在一起。 each_file[2]内的内容将随机在内容each_file[1]之前。从印刷文件列表输出元组随机切换顺序列表

实施例:

[{ef1, ef2}, {ef1, ef2} {ef2, ef1}, {ef1, ef2} ....] 

约约下面的代码信息:
projectDict是pandas.dataframe对象的列表

filelist = [] 
for each_dict in projectDict: 
    currentDataFrame = projectDict[each_dict] 

    for each_file in currentDataFrame.itertuples(): 
     important_terms = { each_file[1], 
          each_file[2]} 
     filelist.append(important_terms) 

这是使用itertuples的结果,还是在我的代码中有另一个明显的错误?我用了iterrows并有同样的问题。我也已经证实,数据不是以输出的方式构成的。

+2

'important_items'是一组,集合是无序的。 –

+2

这些是**不是**元组,但是**集**和**集的顺序未确定**。 –

+0

非常感谢,这是非常愚蠢的错误! – Matthew

回答

3

你写:

important_terms = {each_file[1],each_file[2]} 
#    ^ curly brackets  ^

现在的语法{a,b,...,z}set。在set中,元素最多出现一次次序未确定。像被写入documentation

set目的是不同可哈希 对象的无序集合。常见用途包括成员资格测试,从序列中删除重复项 ,并计算数学运算,如交集,联合,差异和对称差异等。

语法为tuple(a,b,...,z)。所以,你应该改变行:

important_terms = (each_file[1],each_file[2]) 
#    ^ round brackets  ^

或者 - 作为@Matthias说 - 你甚至可以省略圆括弧只有使用逗号:

important_terms = each_file[1],each_file[2] 
#    ^  no brackets  ^

不过,你可以在这里使用切片由于each_file已经是一个元组:

important_terms = each_file[1:3]

在这里,你从指数1(含)切片ŧ索引3(不含)。

最后,你可以使用列表理解把你整个程序一个衬垫

filelist = [each_file[1:3] for each_dict in projectDict 
          for each_file in projectDict[each_dict].itertuples()]

甚至更​​优雅:

filelist = [each_file[1:3] for each_dict in projectDict.values() 
          for each_file in each_dict.itertuples()]
+1

你甚至不需要圆括号。 'important_terms = each_file [1],each_file [2]'就够了,但括号可以作为视觉帮助添加。 – Matthias

+0

@Matthias:同意。不过,我认为它可能有用。但我会在答案中加上一个注释。 –