comparing lists and highlight the key elements

473 views Asked by At
from colorama import Fore, init
init()

key_numbers = [1,3,5,7,9]
numbers  = [3,4,6,3,8,9,7,9,3,1]

for number in numbers:
       if number in key_numbers: 
           number1 = Fore.RED + number 
           numbers = [number1 if number else number for number in numbers] 
      else:
          continue 

Essentially I want the code to go through each number in the numbers list and check whether the respective number exists in the key_numbers list.

If it exists, I want to replace the number with red font and move on to the next number

The output should have a list with numbers highlighted in red if they exist in the key_numbers list and the other numbers in regular font and color.

I think I am going wrong trying to replace the numbers with number1. Can someone please help me where I am going wrong?

2

There are 2 answers

2
Clem Niem On

You can check out the map operator:

items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))

You don't need to provide a lambda. You can also explicitly define a Function that returns a red number if it is in keys and otherwise a black one.

E.g.

from colorama import Fore, init
init()

key_numbers = [1,3,5,7,9]
numbers  = [3,4,6,3,8,9,7,9,3,1]

def highlight(number):
    if number in key_numbers:
        return Fore.RED + str(number)
    else:
        return str(number)

colored_numbers = list(map(highlight, numbers))
0
Daniel Schütte On

The code below will take your two lists and print a colorful output, highlighting those list items from numbers that are also part of number_keys. Let me know if that's what you wanted to achieve!

#!/usr/bin/python3
from colorama import init, Fore, Style

# init colorama
init()

def highlight(numbers, keys):
    """
    check if numbers exists in keys and
    print + highlight them in red.
    """
    for number in numbers:
        if number in keys:
            print(Fore.RED + str(number) + Style.RESET_ALL, end=" ")
        else:
            print(number, end=" ")
    print()  # print another "\n"

# define numbers and keys
key_numbers = [1, 3, 5, 7, 9]
numbers  = [3,4,6,3,8,9,7,9,3,1]

print("numbers to highlight: {}".format(key_numbers))

# call highlight()
highlight(numbers, key_numbers)