kent chan
kent chan

Reputation: 13

Arranging python array

When I run the following code:

array1 = ["happy", "sad","good", "bad","like"]
array2=["i like starhub", "i am happy with the starhub service", "starhub is      bad"," this is not awful"]

for i in array1:
    for j in array2:
        if i in j :
            print i

The result printed will be

happy
bad
like

The output is printed according to the order they're listed in array1. How can I sort the output according to array2? I would like the output to be:

like
happy
bad

Upvotes: 0

Views: 100

Answers (2)

Michael Geary
Michael Geary

Reputation: 28850

Leb's answer is right on the money; please upvote and accept it.

I just want to add a note about naming conventions.

In many programming languages, variable names i and j are traditionally used for numeric loop indexes, but not for the actual values of the elements in a list or array.

For example (pun intended), if you were writing an old-fashioned for loop in JavaScript, it might look like this:

var names = [ "Kent", "Leb", "Dalen" ];
for( var i = 0;  i < names.length;  i++ ) {
    console.log( names[i] );
}

You could also write code like this in Python, but since you're using the more expressive Python for loop, you can use better names than i and j.

As Dalen notes in a comment, the names array1 and array2 don't match Python terminology—but more importantly, they don't say anything about what is in these lists.

It is helpful to use more self-explanatory variable names throughout. In your code, the two lists are a list of words and a list of phrases, and the variables in the loops represent a single word and a single phrase.

A convention I like here is to use a plural name for a list or array, and the corresponding singular name for an individual element of that list or array.

So you could use names like this:

words = [ "happy", "sad", "good", "bad", "like" ]
phrases = [
    "i like starhub",
    "i am happy with the starhub service",
    "starhub is bad",
    " this is not awful"
]

for phrase in phrases:
    for word in words:
        if word in phrase:
            print( word )

Do you see how much more clear this makes the code? Instead of i and j and array1 and array2 (or list1 and list2), each name describes the actual data you're working with.

Upvotes: 1

Leb
Leb

Reputation: 15953

Switch the loop:

list1 = ["happy", "sad", "good", "bad", "like"]
list2 = ["i like starhub", "i am happy with the starhub service", "starhub is bad", " this is not awful"]

for j in list2:
    for i in list1:
        if i in j:
            print(i)


>>like
>>happy
>>bad

The one on top is what's being used as the primary list. So in your case, list1 was the primary and being sorted as such.

In the one I gave, list2 is the primary instead.

Upvotes: 3

Related Questions