我有一个代码应该打印出从最短到最长的升序排序的10行。我有一个测试文本,我想使用位置线[4]中的字段len来排序输出行,但我不知道怎么做,因为我认为我需要阅读整个文本并在订购之后在第5场的长度函数中的线。
#!/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()
我希望最终结果是:
"" "" "" "" "22" ""
"" "" "" "" "333" ""
"" "" "" "" "4444" ""
"" "" "" "" "55555" ""
"" "" "" "" "666666" ""
"" "" "" "" "7777777" ""
"" "" "" "" "88888888" ""
"" "" "" "" "999999999" ""
"" "" "" "" "1000000000" ""
"" "" "" "" "11111111111" ""
我该怎么做?
答案 0 :(得分:0)
将映射器方法更改为此
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)