dya
dya

Reputation: 195

select the maximum value from array python

How to get the sublist with the maximum length within a list?

I have this codes:

c = [1,2]
a = [[1,2], [3,4], [3,2]]
for b in a:
    g = len(list(set(b) - set(c))) *#list of difference items between c and b in a*
    print(g)

result

0
2
1

I need to get b in a with the longest length >> g = 2

I used

y = [b for b in a if max (g)]

TypeError: 'int' object is not iterable

Thank you,

Upvotes: 3

Views: 1117

Answers (2)

AChampion
AChampion

Reputation: 30258

max(g) doesn't really make much sense because g is just the last int value (1) in the previous loop. max() expects an iterable - hence your error. But even fixing g to be the list [0, 2, 1] your guard in the list comprehension wouldn't really do anything because it would always evaluate to True because it is equivalent to writing if 2.

But you can rewrite your code with max() using the key to calculate the difference:

>>> c = [1,2]
>>> a = [[1,2], [3,4], [3,2]]
>>> max(a, key=lambda x: len(set(x)-set(c)))
[3, 4]

Upvotes: 4

Shanaka Anuradha
Shanaka Anuradha

Reputation: 388

You can try this one

c = [1,2]
a = [[1,2], [3,4], [3,2]]
k=max(max(map(lambda x:set(c)-set(x),a)))
print k if k else 0

Upvotes: 0

Related Questions