0
10行を最短から最長の昇順にソートして出力するコードが1つあります。私はテストテキストを持っていますが、私は位置行[4]のフィールドのlenを使って出力行を並べ替えることを望みますが、私はテキスト全体を読む必要があると思うので、それを行う方法はわかりません第5フィールドの長さの関数としての線。どのように各行のフィールドのlenで行を並べ替えることができますか? Python
#!/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" ""
私はこれをどのように行うことができますか?
へのマッパー方法(リスト(リーダー)、キー=ラムダX:LEN(X [-2])): lenの場合(ライン[-2] )> 1: writer.writerow(line) – zorro
ありがとうございます;) – zorro
よろしくお願いします。 – danidee