2016-10-25 12 views
1

誰かが特定の単語のスペルで辞書を注文する方法を知っていたのだろうか?辞書はソートされていないので、OrderedDictの使用に頼っていましたが、キーと値だけでソートできると思います。この方法でそれを注文する方法の任意のアイデアですか?単語のスペルで辞書を注文する - Python 3

ここで私が働いていたプロジェクトの一部です:

word = input("word") 
list_1 = list(word) 

word>? apple 

len_list_1 = len(list_1) 


dict = {} 

for x in range(0, len(list_1)): 
    dict[list_1[x]] = list_1.count(list_1[x]) 

print(dict) 

>{'l': 1, 'p': 2, 'a': 1, 'e': 1} 

私は言葉「リンゴ」のためにそれを維持して、何とかプレーンテキストに辞書を変換しようとしていた。

{'a' : 1, 'p': 2, 'l': 1, 'e': 1} 
> a1p2l1e1 #as my final answer 
最初のポイントとして
+1

単語を「最初に見た」順序で並べ替えるだけですか? 'ミシシッピ'は '{'m':1、 'i':4、 's':4、 'p':2}'/'m1i4s4p4'となるでしょうか? –

+0

@AndrewGelnarはい、それは私がそれが必要な方法です。 –

答えて

3

、あなたのコードは非常にシンプルな何かをするのはかなり非効率的とunpythonic方法であることに注意してください:

>>> from collections import Counter 
>>> Counter('apple') 
Counter({'p': 2, 'a': 1, 'e': 1, 'l': 1}) 

(毎回すべての文字をカウントしているため、非効率的です。 'aaaaa'は 'a'を5回カウントします。あなたが宣言し、長さ変数とループスローを使用しないでください。range(len(...))はほとんどお勧めできません。

このカウンタをソートしてOrderedDictにすることができます。

>>> word = 'apple' 
>>> c = Counter(word) 
>>> OrderedDict(sorted(c.items(), key=lambda x: word.index(x[0]))) 
OrderedDict([('a', 1), ('p', 2), ('l', 1), ('e', 1)]) 

注あなたは、単に文字をグループ化している場合答えは非常に異なるものになること:あなたが'b1o1b1'のような何かをしたい場合は辞書には、右のデータ構造ではない私は、単語の最初の発生によってソートしています。

ご希望の出力は単なる文字列'a1p2l1e1'ある場合は、次の操作を実行できます

>>> word = 'apple' 
>>> c = Counter(word) 
>>> sorted_letter_counts = sorted(c.items(), key=lambda x: word.index(x[0])) 
>>> ''.join(c + str(n) for c,n in sorted_letter_counts) 
'a1p2l1e1' 

またはワンライナーとして:

>>> word = 'apple' 
>>> ''.join(c + str(n) for c,n in sorted(Counter('apple').items(), key=lambda x: word.index(x[0]))) 
'a1p2l1e1' 
+0

ありがとう!私はあなたの事例でそんなに学んだことがあります。私はPythonには新しく、Pythonicとは何かを理解しようとしています。 –

0

Straight from the docs

class OrderedCounter(collections.Counter, collections.OrderedDict): 
    'Counter that remembers the order elements are first encountered' 

    def __repr__(self): 
     return '%s(%r)' % (self.__class__.__name__, collections.OrderedDict(self)) 

    def __reduce__(self): 
     '''__reduce__ is for pickling''' 
     return self.__class__, (collections.OrderedDict(self),) 

を使用法:

>>> foo = OrderedCounter('apple') 
>>> foo 
OrderedCounter(OrderedDict([('a', 1), ('p', 2), ('l', 1), ('e', 1)])) 
>>> 

>>> for thing in foo.items(): 
    print(thing) 


('a', 1) 
('p', 2) 
('l', 1) 
('e', 1) 
>>> 
関連する問題