2017-03-09 92 views
0

是否有一种方法可以将count()用于整个列表,而不必单独在每个变量上使用它?如果这是可能的话,这将节省我很多打字。你可以使用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'需要两个参数,而不是一个。 'list'是一个类型,所以我不认为你想重新分配它,'.count'不是'daysPerWk'的方法,甚至没有定义。 – Scovetta

+0

@scovetta那里。我是编码新手。对不起,它不明确。它应该是现在。 –

回答

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出现在列表中的次数。

如果你想知道每个项目多少次出现在列表中,如果它出现在列表中,你可以这样做:

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) 

应打印出类似这样

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

下面是对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)) 

,这应该打印与上述相同的字典。

相关问题