Comparing strings in a list?

Saif :

I have a set of strings in a list, the list is given below in the code. I would like to compare each string to its previous strings. Obviously the first positioned string will not be compared with previous string since there isn't any. The logic is basically: 2nd positioned string to be compared with 1st positioned string, 3rd positioned string to be compared with 1st and 2nd positioned string, ... ...

s = ["avocado", "banana", "carrot", "avocado", "carrot", "grapes", "orange"]
for i in range(2,len(s)):
    for j in range(i,2, -1):
        if s[i] == s[j]:
            print (s[i])

Now, if there is a match found, the string name with the positions will be shown. Such as avocado found in position 4 and 1. I am stuck at this code. How should I proceed?

Michael Bianconi :
s = ["avocado", "banana", "carrot", "avocado", "carrot", "grapes", "orange"]
for i in range(1, len(s)):
    for j in range(i):
        if s[i] == s[j]:
            print(s[i])

You were close. Use range(i) to count from 0 to i. Use an index of 1 to get the second item in the list (lists start at 0).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=3963&siteId=1
Recommended