- Goal
リスト型の要素の中の重複排除とNone(空要素)を排除する。
集合型(set)なら、重複排除は自動でできて、.discardでNoneは排除可能だが、リスト型で行いたい。理由は、リスト内の順番をキープしたいから。 - How
if で要素があるかどうか?と長さが0より大きいかを確認する。
※filterを使うとか、内包表記を使うとか色々載っていたが、これが一番分かりやすかった。。。This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters# -*- coding: utf-8 -*- import unicodedata inputtext = u'Aaa\nbBbb\n\nCCddff\n\nAaa\n\n' inputlist3 = [] # 全角を半角へ、小文字を大文字へ変換 itemcode = unicodedata.normalize('NFKC', inputtext).upper() # 改行区切りでリストに代入 inputlist = list(itemcode.replace(' ','\n').replace(' ','\n').split('\n')) # 改行区切りでリストに代入 でも、最後の改行は排除 inputlist2 = list(itemcode.replace(' ','\n').replace(',','\n').splitlines()) # 重複排除と長さの確認 for x in inputlist: if x not in inputlist3 and len(x) > 0 : inputlist3.append(x) print "=== inputtext" print inputtext print "=== after normalize" print itemcode print "=== normal list splitted by \\n" print inputlist print "=== normal list with splitlines" print inputlist2 print "=== eliminating duplication and None" print inputlist3 - Result
~$ python eliminating_duplication.py=== inputtextAaabBbbCCddffAaa=== after normalizeAAABBBBCCDDFFAAA=== normal list splitted by \n[u'AAA', u'BBBB', u'', u'CCDDFF', u'', u'AAA', u'', u'']=== normal list with splitlines[u'AAA', u'BBBB', u'', u'CCDDFF', u'', u'AAA', u'']=== eliminating duplication and None[u'AAA', u'BBBB', u'CCDDFF']
Oracle Application Express Notes | Apps development Notes | Google Cloud Platform | Python | apps test | Cool Beans | English | Books
2018/07/29
リストの要素の重複排除とNone(空要素)の排除 − Python
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿