Select maximum value from python array

How do I get the sublist with the maximum length in the list?

I have these 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,

+3


source to share


2 answers


max(g)

doesn't really make a lot of sense, because g

- it's only the last value int

( 1

) in the previous loop. max()

expects iterable - hence your mistake. But even committing g

to be a list [0, 2, 1]

, your guardian in list comprehension wouldn't do anything, because he would always evaluate to True

, because that's the equivalent of writing if 2

.

But you can rewrite your code using max()

using 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]

      

+4


source


You can try this



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

      

0


source







All Articles