0

Pretty new to Python and have been playing around with lists and the sort member. My question is if I have a list of random strings (all strings of equal length):

li=["hgjtud", "iernfd", "scoeps", "stiiss", "stripe"]

and now I want to sort that list according to some rank which I define with the following function:

def rank_string(str1,str2):
    rank=0
    for i in range(len(str1)): #all strings will be checked to be equal length
        if (str1[i]==str2[i]):
            rank += 1
    return rank

and now I want to sort my list using this function together with a target string, so I try the following:

target_string="stripe"
df = lambda x:rank_string(x,target_string)
sorted_list = resultlist.sort(key=df)

I was of the impression that all list values will be given a key after one pass of the ranking function and thereafter be sorted according to this? This runs, but sorted_list has value None. I assume then that being a n00b, I am missing something fundamental. What? :-)

Thanks for the help in advance.

4 Answers 4

1

The .sort() method sorts in-place and doesn't return anything.

Use sorted() instead if you want the sorted list returned and the original input list left untouched.

>>> a = [2, 3, 1]
>>> a.sort()
>>> a
[1, 2, 3]
>>> b = [2, 3, 1]
>>> sorted(b)
[1, 2, 3]
>>> b
[2, 3, 1]
Sign up to request clarification or add additional context in comments.

Comments

1

As other said, sorted() will return a new list. Your code could look like this:

li = ["hgjtud", "iernfd", "scoeps", "stiiss", "stripe"]
target_string = "stripe"

sorted_list = sorted(li, key=lambda x: sum(1 for c1,c2 in zip(x, target_string) if c1==c2))

returns ['hgjtud', 'iernfd', 'scoeps', 'stiiss', 'stripe']

1 Comment

I'm beginning to realize that terseness is very pythonesque :-) and is the way to go. Thanks.
1

Like the others said, use sorted(). Also you could make things shorter:

from functools import partial

def rank_string(str1, str2):
    return sum(a == b for a, b in zip(str1, str2))

li = ["hgjtud", "iernfd", "scoeps", "stiiss", "stripe"]
sorted_list = sorted(li, key=partial(rank_string, "stripe"))

[EDIT]

from operator import eq

def rank_string(str1, str2):
    return sum(map(eq, str1, str2))

:-)

[/EDIT]

1 Comment

again, I guess the terseness comes with the familiarity .-)
0

resultlist.sort is a method of list, sorts resultlist in place, and returns None.

sorted_list = sorted(li, key=df) should do the trick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.