从子列表创建布尔列表。 Python 2.7

时间:2014-04-03 22:45:27

标签: python list for-loop boolean sublist

data = [ [['name1','name1','name1'],[0,0,2],[1000,1200,30],['--','No','Yes']],[['name2','name2'],[0,0,0],[1000,1100],['--','No']], [['name3'],[1],[1234],['--']] ]

在数据列表中有SUBLISTS,每个SUBLISTS包含3个子列表

在这种情况下,我有包含3个SUBLISTS的数据列表,每个SUBLISTS有3个子列表。 。 。大小分别为3,2和1。

#sublist1 has repeating name strings (of X elements) *all of these elements are the same
#sublist2 has a series of integers (of X elements)
#sublist3 has a series of integers (of X elements)
#sublist4 has a series of strings (of X elements) *these elements can include 'No','--', or 'Yes'

基本上我要做的是创建一个新列表,提供

#1) item[0] the name in the first sublist
#2) item[1] a '1' if at least one of the values in sublist2 is > 0 . . . or else print a '0'
#3) item[2] a '1' if at least one of the values in sublist3 is >= 1200 . . . or else print a '0'
#4) item[3] a '1' if at least one of the strings in sublist4 == 'Yes' . . . or else print a '0'
输出应该是:

output = [ ['name1','1', '1','1'],['name2','0','0','0'],['name3','1','1','0'] ]

我已经尝试了一段时间,但我还没有走得太远。以这种格式获取数据非常困难。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

可能效率不高,但可读:

>>> [[i[0][0],
... int(any([1 for j in i[1] if j>0])),
... int(any([1 for j in i[2] if j>=1200])),
... int(any([1 for j in i[3] if j=='Yes']))] for i in data]
[['name1', 1, 1, 1], ['name2', 0, 0, 0], ['name3', 1, 1, 0]]
如果列表中的一个元素为true,则{p> any返回True,int(True)为1。