Home > Net >  If list contains an item, then list equals to item
If list contains an item, then list equals to item

Time:12-29

I don't know how to formulate the question correctly: I have a list of lists, which contains multiple items.

mylist=[['a','b','c','₾'],['x','t','f','₾'],['a','d'],['r','y'],['c','₾'],['a','b','c','i'],['h','j','l','₾']]

If any of the lists contains symbol '₾', I want to append the symbol to another list, else append None.

result=[]
for row in mylist:
    for i in row:
        if i=='₾':
            result.append(i)
        else:
            result.append(None)
result

But I want to get this result :

result=['₾','₾',None,None,'₾',None,'₾']

CodePudding user response:

That would be:

result = ['₾' if '₾' in sublist else None for sublist in mylist]

CodePudding user response:

result = []
for row in mylist:
    if '₾' in row:
        result.append('₾')
    else:
        result.append(None)

CodePudding user response:

>>> mylist=[['a','b','c','₾'],['x','t','f','₾'],['a','d'],['r','y'],['c','₾'],['a','b','c','i'],['h','j','l','₾']]
>>> c = '₾'
>>> [c if c in row else None for row in mylist]
['₾', '₾', None, None, '₾', None, '₾']

CodePudding user response:

A small edit to your code can be done to get the desired result

mylist=[['a','b','c','₾'],['x','t','f','₾'],['a','d'],['r','y'],['c','₾'],['a','b','c','i'],['h','j','l','₾']]

result=[]
for row in mylist:
    if '₾' in row:
        result.append(i)
    else:
        result.append(None)
result

Output

['₾', '₾', None, None, '₾', None, '₾']

The above code can be reduced into a line of List Comprehension

['₾' if '₾' in row else None for row in mylist]
  • Related