2016-08-15 103 views
0

我列出了我转换成numpy的数组列表索引和元素的最大值:返回一个列表中的元素基于另一个列表

lsts = ([[1,2,3], ['a','b','a']], 
     [[4,5,6,7], ['a','a','b','b']], 
     [[1,2,3],['b','a','b']]) 

np_lsts = np.array(lsts) 

我想返回最大的元素在第一个列表中'b'出现在第二个列表中。我想我必须使用索引,但我坚持!

即我想回到(2,7,3)在这种情况下

回答

1

这将做到:

[max(u for u,v in zip(x,y) if v=='b') for x,y in lsts if 'b' in y] 

嵌套列表理解使用zip()max()

+0

这如果第二列表中不包含失败a'b'。例如:'lsts =([[1,2,3],['a','c','e']])' –

+0

@CraigBurgler我编辑了答案,并修复了第二个列表不包含的问题 –

1

一个可能的解决方案到你的问题:

lsts = ([[1, 2, 3], ['a', 'b', 'a']], 
     [[4, 5, 6, 7], ['a', 'a', 'b', 'b']], 
     [[1, 2, 3], ['b', 'a', 'b']], 
     [[1, 2, 3], ['a']] 
     ) 

result = [] 
for l in lsts: 
    indices = [l[0][index] for index, v in enumerate(l[1]) if v == 'b'] 
    if indices: 
     result.append(max(indices)) 

print result 
+0

a'b',代码试图追加'max([])',这会产生语法错误 –

+0

@CraigBurgler好的!在这种情况下,我编辑了代码以使其工作;) – BPL

0
def get_max(l): 
    first = True 
    for e1, e2 in zip(l[0], l[1]): 
     if e2 == 'b' and first: 
      max = e1 
      first = False 
     elif e2 == 'b' and e1 > max: 
      max = e1 
    return max 

result =() 
for l in lsts: 
    if 'b' in l[1]: 
     result += (get_max(l),) 
print(result) 
1

以下函数返回result列表。如果需要,您可以返回一个元组而不是列表。

def maxNum(lsts, character): 
    result = [] 
    for entry in lsts: 
     if character in entry[1]: 
      result.append(max(entry[0])) 
    return result 

# lsts = ... # (put lsts here) 

print maxNum(lsts, 'b') 
+0

这将返回OP示例的[3,7,3]。 –

0

这应该是很多比当前解决方案更加有效,如果子列表有很多的元素,因为它是矢量对这些子列表:

import numpy_indexed as npi 
results = [npi.group_by(k).max(v) for v,k in lsts] 
相关问题