我列出了我转换成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)在这种情况下
我列出了我转换成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)在这种情况下
一个可能的解决方案到你的问题:
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
a'b',代码试图追加'max([])',这会产生语法错误 –
@CraigBurgler好的!在这种情况下,我编辑了代码以使其工作;) – BPL
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)
以下函数返回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')
这将返回OP示例的[3,7,3]。 –
这应该是很多比当前解决方案更加有效,如果子列表有很多的元素,因为它是矢量对这些子列表:
import numpy_indexed as npi
results = [npi.group_by(k).max(v) for v,k in lsts]
这如果第二列表中不包含失败a'b'。例如:'lsts =([[1,2,3],['a','c','e']])' –
@CraigBurgler我编辑了答案,并修复了第二个列表不包含的问题 –