Is there a way to replace an integer in a list, with a string from another list at random?

74 Views Asked by At

I have a list of words which are also assigned a numerical value

words = [[Happy,1],[Sad,2],[Anger,3]]

I then have two additional lists, of just words and integers, produced in earlier code

List1 = [Happy,2,3,1,1,Sad,Sad,Anger]
List2 = [1,Sad,Anger,Happy,Happy,2,2,3]

I need to replace the integers, with strings from the words list. However I also need to make it so that the words in each index for List1 and List2 are not the same. I cannot use shuffle as I need to keep the order.

I was looking into 'isintance' as a way of checking for integers and replacing them, but I am unsure as to how I'd go about the random element of it.

2

There are 2 best solutions below

0
On BEST ANSWER

I would base my initial attempt off of looking at the two lists a pair of items at a time. If one or both members of the pair are not strings then find a random replacement that is not equal to the other item in the pair.

import random

List1 = ["Happy",2,3,1,1,"Sad","Sad","Anger"]
List2 = [1,"Sad","Anger","Happy","Happy",2,2,3]

## ----------------------
## Find replacement words.
## unless we reshape words to be a dictionary
## there is probably no need to track the "number"
## ----------------------
words = [["Happy",1], ["Sad",2], ["Anger",3]]
valid_words = [p[0] for p in words]
## ----------------------

## ----------------------
## iterate over our pair of lists.
## ----------------------
for index, (l1, l2) in enumerate(zip(List1, List2)):
    ## ---------------------
    ## If item "0" is not a string, find a replacement
    ## ---------------------
    if not isinstance(l1, str):
        List1[index] = random.choice(list(w for w in valid_words if w != l2))
    ## ---------------------

    ## ---------------------
    ## if item "1" is not a string, find a replacement
    ## ---------------------
    if not isinstance(l2, str):
        List2[index] = random.choice(list(w for w in valid_words if w != l1))
    ## ---------------------
## ----------------------

for pair in zip(List1, List2):
    print(pair)

That will give you something like:

('Happy', 'Sad')
('Anger', 'Sad')
('Happy', 'Anger')
('Anger', 'Happy')
('Anger', 'Happy')
('Sad', 'Happy')
('Sad', 'Anger')
('Anger', 'Happy')

Note that this updates the two lists "in place" and if you wanted to not mutate those lists we would need a slightly different set of code to build two new lists via append(). The logic however would be mostly the same.

0
On

Does this code resolve your issue?

import random
words = [['Happy', 1], ['Sad', 2], ['Anger', 3]]
replacement_strings = ['Excited', 'Depressed', 'Furious']

for item in words:
    if isinstance(item[1], int):
        random_string = random.choice(replacement_strings)
        item[1] = random_string

print(words)