简体   繁体   中英

How can I sort lines by the len of a field of each line? Python

I have one code that should print out 10 lines sorted in ascending order from shortest to longest. I have a test text and I want to order the output lines using the len of the field in the position line[4] but I don´t know how to do it because I think I need to read the entire text and after to order the lines in function of the lenght of the 5th field.

#!/usr/bin/python
import sys
import csv


def mapper():
    reader = csv.reader(sys.stdin, delimiter='\t')
    writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)

    for line in reader:
           line.sort(key=len)
           writer.writerow(line)



test_text = """\"\"\t\"\"\t\"\"\t\"\"\t\"333\"\t\"\"
\"\"\t\"\"\t\"\"\t\"\"\t\"88888888\"\t\"\"
\"\"\t\"\"\t\"\"\t\"\"\t\"1\"\t\"\"
\"\"\t\"\"\t\"\"\t\"\"\t\"11111111111\"\t\"\"
\"\"\t\"\"\t\"\"\t\"\"\t\"1000000000\"\t\"\"
\"\"\t\"\"\t\"\"\t\"\"\t\"22\"\t\"\"
\"\"\t\"\"\t\"\"\t\"\"\t\"4444\"\t\"\"
\"\"\t\"\"\t\"\"\t\"\"\t\"666666\"\t\"\"
\"\"\t\"\"\t\"\"\t\"\"\t\"55555\"\t\"\"
\"\"\t\"\"\t\"\"\t\"\"\t\"999999999\"\t\"\"
\"\"\t\"\"\t\"\"\t\"\"\t\"7777777\"\t\"\"
"""

# This function allows you to test the mapper with the provided test string
def main():
    import StringIO
    sys.stdin = StringIO.StringIO(test_text)
    mapper()
    sys.stdin = sys.__stdin__
main()

I want that the final result is:

"" "" "" "" "22" "" 
"" "" "" "" "333" "" 
"" "" "" "" "4444" "" 
"" "" "" "" "55555" "" 
"" "" "" "" "666666" "" 
"" "" "" "" "7777777" "" 
"" "" "" "" "88888888" "" 
"" "" "" "" "999999999" "" 
"" "" "" "" "1000000000" "" 
"" "" "" "" "11111111111" ""

How can I do this?

Change your mapper method to this

def mapper():
    reader = csv.reader(sys.stdin, delimiter='\t')
    writer = csv.writer(sys.stdout, delimiter='\t', quotechar='"', quoting=csv.QUOTE_ALL)

    for line in sorted(list(reader), key=lambda x: len(x[-2])):
        writer.writerow(line)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM