max
max

Reputation: 314

Sorting list of strings by a character

I got the following assignment:

For a given list of strings write a function that returns a sorted list with all strings starting with the character x at the beginning (define two lists)

I stuck here:

set_words_list = ["argentinax", "football", "ss", "poxland", "axmerica"]
set_words_list.sort(key=str("x"))
print(set_words_list)

And then error pops out:

Traceback (most recent call last):
  File "/5SortList/main.py", line 7, in <module>
    set_words_list.sort(key=str("x"))
TypeError: 'str' object is not callable

It is my first time coding in Python, and I have no clue where to go from there. On top of that, according to the task one needs to use 2 lists, yet I don't know how it can help me.

Upvotes: 0

Views: 916

Answers (3)

Leander
Leander

Reputation: 423

set_words_list = ["argentinax", "football", "ss", "poxland", 'xamerica' ,"axmerica"]

x_first_letter = sorted([x for x in set_words_list if x[0]=='x'])
nox_first_letter = sorted([x for x in set_words_list if not x[0]=='x'])

Upvotes: 0

Rima
Rima

Reputation: 1455

list.sort(reverse=True|False, key=myFunc)

reverse --> Optional. reverse=True will sort the list descending. Default is reverse=False
key-->  Optional. A function to specify the sorting criteria(s)

In below code we are passing myFunc to the key part of the sort function. Function returns not e.startswith('x') since True == 1. This will sort the words starting with 'x'.

def myFunc(e):
    return  not e.startswith('x')

set_words_list = ["argentinax", "football", "ss", "poxland", "axmerica", 'xx']

set_words_list.sort(key=myFunc)
print(set_words_list)

Upvotes: 1

Barmar
Barmar

Reputation: 780842

The simplest way is to split the input into two lists. One contains the elements that start with x, the other contains the rest. That's what the instructions meant by "define two lists".

Then sort each of these lists and concatenate them.

x_words = []
nox_words = []
for word in set_words_list:
    if word.startswith("x"):
        x_words.append(word)
    else:
        nox_words.append(word)

result = sorted(x_words) + sorted(nox_words)

Upvotes: 1

Related Questions