2016-08-15 157 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] 
相關問題