Home > Net >  How do I compare two letters or values in two different lists?
How do I compare two letters or values in two different lists?

Time:05-13

I am making a program that has two lists (in Python), and each list contains 5 different letters. How do I make it so that any index number I choose for both lists gets compared and uppercase a letter if the condition is true? If the first two values in the list are the same (in my case a lowercase letter), then I want the letter in the second list to become uppercase.

example/attempt (I don't know what I'm doing):

if list1[0] = list2[0]:
   upper(list2[0])

CodePudding user response:

Without an example of you input and output, it's difficult to understand what your goal is, but if your goal is to use .upper() on any string in list2 where list1[i] and list2[i] are equal, you can use a combination of zip and enumerate to compare, and then assign the value of list2[i] to the uppercase string like so:

list1 = ['a', 'b', 'c']
list2 = ['a', 'p', 'q']

for i, (x, y) in enumerate(zip(list1, list2)):
    if x == y:
        list2[i] = y.upper()

print(list2)

Output:

['A', 'p', 'q']

CodePudding user response:

I think you could use something like this:

def compare_and_upper(lst1, lst2):
    for i in range(len(lst1)):
        if lst1[i].upper() == lst2[i].upper():
            return lst1[i].upper()
    return None

CodePudding user response:

This is not a full solution of your problem, more of a representation of how to do the comparisons, which you can then reuse / modify to do the solution you want in the end.

import string
from random import choices

def create_random_string(str_len=10):
    # k = the number of letters that we want it to return.
    return "".join(choices(string.ascii_lowercase, k=str_len))

def compare(str_len=10):
    # Create the two strings that we want to compare
    first_string = create_random_string(str_len)
    second_string = create_random_string(str_len)

    # comp_string will hold the final string that we want to return.
    comp_string = ""
    
    # Because the length of the strings are based on the variable str_len, 
    # we can use the range of that number to iterate over our comparisions.
    for i in range(str_len):
        # Compares the i'th position of the strings
        # If they match, then add the uppercase version to comp_string
        if first_string[i] == second_string[i]:
            comp_string  = first_string[i].upper()
        else:
            comp_string  = "-"
    
    return comp_string

for _ in range(10):
    print(compare(20))

Sample output:

--------------------
---AS---D---------D-
----W--Q--------E---
--------------------
-----------------E--
------T-------------
--------------------
-------------P------
-----S--------------
--B-----------------
  • Related