patternpythonMajor
Sorting strings by length - functional Python
Viewed 0 times
sortinglengthpythonfunctionalstrings
Problem
I'm trying to port this little F# snippet while staying pythonic:
In case you don't speak F#, it gets the length of each string, then sorts by length.
Output:
In Python, this is the best I could do so far:
While correct, this doesn't look very elegant to me, or maybe it's just my non-pythonic eye.
Is this pythonic code? How would you write it? Maybe an imperative style is more appropriate?
["something"; "something else"; "blah"; "a string"] |> List.map (fun p -> p, p.Length) |> List.sortBy sndIn case you don't speak F#, it gets the length of each string, then sorts by length.
Output:
[("blah", 4); ("a string", 8); ("something", 9); ("something else", 14)]In Python, this is the best I could do so far:
sorted([(p, len(p)) for p in ["something", "something else", "blah", "a string"]], key=lambda a:a[1])While correct, this doesn't look very elegant to me, or maybe it's just my non-pythonic eye.
Is this pythonic code? How would you write it? Maybe an imperative style is more appropriate?
Solution
data = ["something", "something else", "blah", "a string"]
result = [(x, len(x)) for x in sorted(data, key = len)]Basically, its more straightforward to sort first then decorate. Although, I'm not sure why you would need the length of the list in your tuple. If you don't really need it sorting by length can be much shorter.
EDIT:
If all I wanted was to output the data, I'd do it like this:
for string in sorted(data, key = len):
print string, len(string)If you really wanted to eliminate the two references to len you could do:
mykey = len
for string in sorted(data, key = mykey):
print string, mykey(string)But unless you are reusing the code with different mykey's that doesn't seem worthwhile.
Code Snippets
data = ["something", "something else", "blah", "a string"]
result = [(x, len(x)) for x in sorted(data, key = len)]for string in sorted(data, key = len):
print string, len(string)mykey = len
for string in sorted(data, key = mykey):
print string, mykey(string)Context
StackExchange Code Review Q#1001, answer score: 29
Revisions (0)
No revisions yet.