質問

だの周波数の要素をリストに

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

出力->

b = [4,4,2,1,2]

でももしあなたのから重複

a = [1,2,3,4,5]
役に立ちましたか?

解決

リストが発注されているので、あなたがこれを行うことができます:

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
from itertools import groupby
[len(list(group)) for key, group in groupby(a)]

出力:

[4, 4, 2, 1, 2]

他のヒント

はPython 2.7以降が導入辞書理解。リストから辞書を構築することは、あなたにカウントを取得しますだけでなく、重複を取り除くます。

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> d = {x:a.count(x) for x in a}
>>> d
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
>>> a, b = d.keys(), d.values()
>>> a
[1, 2, 3, 4, 5]
>>> b
[4, 4, 2, 1, 2]

出現回数をカウントします:

from collections import defaultdict

appearances = defaultdict(int)

for curr in a:
    appearances[curr] += 1

重複を削除するには:

a = set(a) 

要素の周波数は、おそらく最高の辞書で行われるカウント

b = {}
for item in a:
    b[item] = b.get(item, 0) + 1

を使用し、セットを重複を削除するには:

a = list(set(a))

でのPython 2.7以降、あなたが使用することができます collections.Counter のアイテムをカウントする。

>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>>
>>> from collections import Counter
>>> c=Counter(a)
>>>
>>> c.values()
[4, 4, 2, 1, 2]
>>>
>>> c.keys()
[1, 2, 3, 4, 5]

いつものようにsuccint代替用 itertools.groupby も作品の順序付けを入力:

from itertools import groupby

items = [5, 1, 1, 2, 2, 1, 1, 2, 2, 3, 4, 3, 5]

results = {value: len(list(freq)) for value, freq in groupby(sorted(items))}

結果

{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}

あなたはこれを行うことができます:

import numpy as np
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
np.unique(a, return_counts=True)

出力:

(array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))

最初の配列は値であり、二番目の配列は、これらの値を持つ要素の数である。

ですから、あなたがこれを使用する必要がある番号の配列だけを取得したい場合:

np.unique(a, return_counts=True)[1]
seta = set(a)
b = [a.count(el) for el in seta]
a = list(seta) #Only if you really want it.
from collections import Counter
a=["E","D","C","G","B","A","B","F","D","D","C","A","G","A","C","B","F","C","B"]

counter=Counter(a)

kk=[list(counter.keys()),list(counter.values())]

pd.DataFrame(np.array(kk).T, columns=['Letter','Count'])

いるのは簡単でscipy.?itemfreq以下のように

from scipy.stats import itemfreq

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

freq = itemfreq(a)

a = freq[:,0]
b = freq[:,1]

ご確認の書類はこちら http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.itemfreq.html

def frequencyDistribution(data):
    return {i: data.count(i) for i in data}   

print frequencyDistribution([1,2,3,4])

...

 {1: 1, 2: 1, 3: 1, 4: 1}   # originalNumber: count

あなたの最初の質問については、反復リストとexistsenceの要素を追跡するために辞書を使用しています。

あなたの2番目の質問については、ちょうど集合演算子を使用します。

この答えはより明確である。

a = [1,1,1,1,2,2,2,2,3,3,3,4,4]

d = {}
for item in a:
    if item in d:
        d[item] = d.get(item)+1
    else:
        d[item] = 1

for k,v in d.items():
    print(str(k)+':'+str(v))

# output
#1:4
#2:4
#3:3
#4:2

#remove dups
d = set(a)
print(d)
#{1, 2, 3, 4}

私はかなり遅れていますが、これはまた意志の仕事、そして他の人を助けるます:

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
freq_list = []
a_l = list(set(a))

for x in a_l:
    freq_list.append(a.count(x))


print 'Freq',freq_list
print 'number',a_l

は、この..

が生成されます
Freq  [4, 4, 2, 1, 2]
number[1, 2, 3, 4, 5]
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

# 1. Get counts and store in another list
output = []
for i in set(a):
    output.append(a.count(i))
print(output)

# 2. Remove duplicates using set constructor
a = list(set(a))
print(a)
  1. セットの収集できない複製、リストの設定()コンストラクタの提案を行います。listの完全なオブジェクト。count()関数が返す整数カウントがオブジェクトがリストが渡されます。その物体の集計対象は、各カウント値を格納を追加することによって空のリスト出力
  2. list()コンストラクタに変換するために使用されます。セット(a)のリストと同じ変数に、

出力

D:\MLrec\venv\Scripts\python.exe D:/MLrec/listgroup.py
[4, 4, 2, 1, 2]
[1, 2, 3, 4, 5]
from collections import OrderedDict
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
def get_count(lists):
    dictionary = OrderedDict()
    for val in lists:
        dictionary.setdefault(val,[]).append(1)
    return [sum(val) for val in dictionary.values()]
print(get_count(a))
>>>[4, 4, 2, 1, 2]

重複を削除し、秩序を維持するために:

list(dict.fromkeys(get_count(a)))
>>>[4, 2, 1]

私はFREQを生成するためのカウンターを使用しています。コードの1行のテキストファイルの単語から辞書

def _fileIndex(fh):
''' create a dict using Counter of a
flat list of words (re.findall(re.compile(r"[a-zA-Z]+"), lines)) in (lines in file->for lines in fh)
'''
return Counter(
    [wrd.lower() for wrdList in
     [words for words in
      [re.findall(re.compile(r'[a-zA-Z]+'), lines) for lines in fh]]
     for wrd in wrdList])

辞書を使用した簡単な解決策ます。

def frequency(l):
     d = {}
     for i in l:
        if i in d.keys():
           d[i] += 1
        else:
           d[i] = 1

     for k, v in d.iteritems():
        if v ==max (d.values()):
           return k,d.keys()

print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))
#!usr/bin/python
def frq(words):
    freq = {}
    for w in words:
            if w in freq:
                    freq[w] = freq.get(w)+1
            else:
                    freq[w] =1
    return freq

fp = open("poem","r")
list = fp.read()
fp.close()
input = list.split()
print input
d = frq(input)
print "frequency of input\n: "
print d
fp1 = open("output.txt","w+")
for k,v in d.items():
fp1.write(str(k)+':'+str(v)+"\n")
fp1.close()

しかしコレクションを使用せずに別のアルゴリズムを持つ別の解決策ます:

def countFreq(A):
   n=len(A)
   count=[0]*n                     # Create a new list initialized with '0'
   for i in range(n):
      count[A[i]]+= 1              # increase occurrence for value A[i]
   return [x for x in count if x]  # return non-zero count
num=[3,2,3,5,5,3,7,6,4,6,7,2]
print ('\nelements are:\t',num)
count_dict={}
for elements in num:
    count_dict[elements]=num.count(elements)
print ('\nfrequency:\t',count_dict)
あなたはpythonで提供内蔵機能を使用することができます。

l.count(l[i])


  d=[]
  for i in range(len(l)):
        if l[i] not in d:
             d.append(l[i])
             print(l.count(l[i])

上記のコードは、自動的にリスト内の重複を除去し、元のリストと重複せず、リスト内の各要素の周波数を出力します。

1つのショットのために二羽の鳥! X D

あなたが任意のライブラリを使用し、シンプルで短い!

それを維持したくない場合は、

このアプローチが試みたことができます

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)

O / P

[4, 4, 2, 1, 2]

に、機能的な答え:

>>> L = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> import functools
>>> >>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc,1)] if e<=len(acc) else acc+[0 for _ in range(e-len(acc)-1)]+[1], L, [])
[4, 4, 2, 1, 2]

このクリーナーばカウントをゼロにしても

>>> functools.reduce(lambda acc, e: [v+(i==e) for i, v in enumerate(acc)] if e<len(acc) else acc+[0 for _ in range(e-len(acc))]+[1], L, [])
[0, 4, 4, 2, 1, 2]

説明:

  • 従って、さまざまな空 acc リスト
  • 場合は、次の要素 eL 以下のサイズ acc, 今回の更新要素: v+(i==e) 手段 v+1 指定されたインデックス iacc は、現在の要素 e, 場合は、以前の値 v;
  • 場合は、次の要素 eL ではequalsのサイズ acc, して拡大 acc の新しい 1.

の要素が限定されていないソートitertools.groupby).だか結果の場合は負の数です。

もう一つの方法は、それを行うには素朴な方法の下に、辞書とlist.countを使用することです。

dicio = dict()

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

b = list()

c = list()

for i in a:

   if i in dicio: continue 

   else:

      dicio[i] = a.count(i)

      b.append(a.count(i))

      c.append(i)

print (b)

print (c)
a=[1,2,3,4,5,1,2,3]
b=[0,0,0,0,0,0,0]
for i in range(0,len(a)):
    b[a[i]]+=1
str1='the cat sat on the hat hat'
list1=str1.split();
list2=str1.split();

count=0;
m=[];

for i in range(len(list1)):
    t=list1.pop(0);
    print t
    for j in range(len(list2)):
        if(t==list2[j]):
            count=count+1;
            print count
    m.append(count)
    print m
    count=0;
#print m
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top