python计算元组中的存在次数



我有一个元组,里面有元组,如下所示:

tup = ((1,2,3,'Joe'),(3,4,5,'Kevin'),(6,7,8,'Joe'),(10,11,12,'Donald'))

这种情况持续不断,数字在这里并不重要。唯一重要的数据是名字。我需要的是计算一个给定名称在元组中出现的次数,并返回一个列表,其中每个项都是一个列表以及它出现的次数

list_that_i_want = [['Joe',2],['Kevin',1],['Donald',1]]

我不想使用任何像Counter这样的模块或集合。我想硬编码这个。实际上,我想对完整的解决方案进行硬编码,甚至不使用".count(("方法。

到目前为止,我得到的是:

def create_list(tuples):
new_list= list()
cont = 0
for tup in tuples:
for name in tup:
name = tup[3]
cont = tup.count(name)  
if name not in new_list:
new_list.append(name)
new_list.append(cont)
return new_list

list_that_i_want = create_list(tup)
print(list_that_i_want)

我得到的输出是:

['Joe',1,'Kevin',1,'Donald',1]

有什么帮助吗?Python新手。

你可以。首先创建一个字典并查找计数。然后将字典转换为列表列表。

tup = ((1,2,3,'Joe'),(3,4,5,'Kevin'),(6,7,8,'Joe'),(10,11,12,'Donald'))
dx = {}
for _,_,_,nm in tup:
if nm in dx: dx[nm] +=1
else: dx[nm] = 1

list_i_want = [[k,v] for k,v in dx.items()]
print (list_i_want)

您可以将for_loop和if语句部分替换为以下一行:

for _,_,_,nm in tup: dx[nm] = dx.get(nm, 0) + 1

输出将是

[['Joe', 2], ['Kevin', 1], ['Donald', 1]]

更新后的代码为:

tup = ((1,2,3,'Joe'),(3,4,5,'Kevin'),(6,7,8,'Joe'),(10,11,12,'Donald'))
dx = {}
for _,_,_,nm in tup: dx[nm] = dx.get(nm, 0) + 1

list_i_want = [[k,v] for k,v in dx.items()]
print (list_i_want)

输出:

[['Joe', 2], ['Kevin', 1], ['Donald', 1]]

使用中介dict:

def create_list(tuple_of_tuples):
results = {}
for tup in tuple_of_tuples:
name = tup[3]
if name not in results:
results[name] = 0
results[name] += 1
return list(results.items())

当然,使用defaultdict,甚至Counter,将是更Python的解决方案。

您可以尝试这种方法:

tuples = ((1,2,3,'Joe'),(3,4,5,'Kevin'),(6,7,8,'Joe'),(10,11,12,'Donald'))
results = {}
for tup in tuples:
if tup[-1] not in results:
results[tup[-1]] = 1
else:
results[tup[-1]] += 1
new_list = [[key,val] for key,val in results.items()]

这里有一个无计数器的解决方案:

results = {}
for t in tup:
results[t[-1]] = results[t[-1]]+1 if (t[-1] in results) else 1
results.items()
#dict_items([('Joe', 2), ('Kevin', 1), ('Donald', 1)])

相关内容

最新更新