2017-03-09 6 views
0

各変数に個別に使用する必要はなく、リスト全体に対してcount()を使用する方法はありますか?これが可能であれば、私は多くの入力を省くことができます。1つの変数ではなく、リスト全体に対してcount()を使用できますか?

var1 = random.randint(u,v) 
var2 = random.randint(w,x) 
var3 = random.randint(y,z) 

listName = [var1,var2,var3] 

listName.count(x) 
listName.count(y) #can you get the count for an entire list instead of having to do them 
listName.count(z) #all seperately? It would be much more efficient. 
+1

'daysPerWk'とは何ですか?定義を表示してください! – nbro

+0

'randint'は2つのパラメータをとり、1つではありません。 'list'は型ですので、私はあなたがそれを再割り当てしたいとは思わないし、' .count'は定義されていない 'daysPerWk'のためのメソッドではありません。 @scovettaそこに – Scovetta

+0

私はコーディングに新しいです。ごめんなさい。それは今あるはずです。 –

答えて

0

ここでは、ランダムな内容のリストを作成し、長さと合計を表示する例を示します。

import random 

my_list = [ 
    random.randint(1, 10), 
    random.randint(1, 10), 
    random.randint(1, 10) 
] 

print("The value of my_list is {0}".format(my_list)) 

print("The length of my_list is {0}".format(len(my_list))) 

print("The sum of my_list is {0}".format(sum(my_list))) 

サンプル出力:

The value of my_list is [4, 8, 4] 
The length of my_list is 3 
The sum of my_list is 16 

は、これはあなたが探していたものですか?

0

list.count(item)は、リストに表示される回数がitemであることを返します。

あなたはそれがリストに表示されている場合、あなたはこれを行うことができ、各項目がリストに表示された回数を知りたい場合は、次の

{ 
    1: 2, 
    2: 1, 
    3: 1, 
    4: 3 
} 
のようなものを印刷する必要があります
original_list = [1, 1, 2, 3, 4, 4, 4] 
uniques = list(set(original_list)) 

counts = {} 
for unique in uniques: 
    counts[unique] = original_list.count(unique) 

print(counts) 

ここ

setデータ型についての詳細情報です:

https://docs.python.org/3/tutorial/datastructures.html#sets

我々はそれに取り組んでいる一方で、あなたもcollections.Counterを使用することができます。

from collections import Counter 
counts = Counter([1, 1, 2, 3, 4, 4, 4]) 
print(dict(counts)) 

、これは上記と同じ辞書を印刷する必要があります。

関連する問題