3

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,

2 Answers 2

4

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.