Home > Back-end >  Question about why this processing of a list of lists fails
Question about why this processing of a list of lists fails

Time:10-22

I'm wondering why this code fails...

I ask if the numeric value 1, part of one of the ini_list sub component is in the list called l, which is a list of lists.

# ini_list = [[1, 2, 5, 10, 7],
# [4, 3, 4, 3, 21],
# [45, 65, 8, 8, 9, 9]]

element = 1

l = [[]]
est_dans_liste = (element in sublist for sublist in l)

if est_dans_liste:
    print("ok")

Note est_dans_liste is is_in_list in English.

CodePudding user response:

IIUC, You need .any() like below:

>>> ini_list = [[1, 2, 5, 10, 7],[4, 3, 4, 3, 21],[45, 65, 8, 8, 9, 9]]
>>> element = -1
>>> [element in sublist for sublist in ini_list]
[False, False, False]
>>> any(element in sublist for sublist in ini_list)
False

>>> element = 1
>>> [element in sublist for sublist in ini_list]
[True, False, False]
>>> any(element in sublist for sublist in ini_list)
True


>>> est_dans_liste = any(element in sublist for sublist in ini_list)
>>> if est_dans_liste:
...    print("ok")

CodePudding user response:

Edit: As pointed out in the comments, this answer is incorrect.


As @ScottHunter pointed out, you've never used ini_list; try uncommenting those 1st three lines, removing the declaration for l = [[]], and changing (element in sublist for sublist in l) to (element in sublist for sublist in ini_list)

ini_list = [[1, 2, 5, 10, 7],
        [4, 3, 4, 3, 21],
        [45, 65, 8, 8, 9, 9]]

element = 1

est_dans_liste = (element in sublist for sublist in ini_list)

if est_dans_liste:
    print("ok")
  • Related