Python 查找元组中每个唯一元素的频率(不使用任何列表概念),并与其单词连接
我尝试了以下代码:Python 查找元组中每个唯一元素的频率(不使用任何列表概念),并与其单词连接,python,tuples,concatenation,word-frequency,Python,Tuples,Concatenation,Word Frequency,我尝试了以下代码: print("Entered tuple :",tup) for x in tup : val=(x,) count=0 for y in tup : if(x==y): count+=1 temp=(x,count) freq+=(temp,) print("\nPrinting tuple in (tuple element,frequency) format : \n") print(f
print("Entered tuple :",tup)
for x in tup :
val=(x,)
count=0
for y in tup :
if(x==y):
count+=1
temp=(x,count)
freq+=(temp,)
print("\nPrinting tuple in (tuple element,frequency) format : \n")
print(freq)
上述代码的实际输出:
Entered tuple : ('1', '2', '3', '4', '1')
Printing tuple in (tuple element,frequency) format element :
(('1', 2), ('2', 1), ('3', 1), ('4', 1), ('1', 2))
在元组中,1重复2次,它也在结果中显示2次。但它在结果中只显示一次
预期产出为:
Entered tuple : ('1', '2', '3', '4', '1')
Printing tuple in (tuple element,frequency) format element :
(('1', 2), ('2', 1), ('3', 1), ('4', 1))
1我已在代码中导入“集合”模块
from collections import Counter
循环中有2个计数器
for x in Counter(tup) :
输出
你可以使用Countertup,我确信这是一个重复的。可能是tupleCounter'1','2','3','4','1'的重复。itemsThanks@Sayse。得到了预期的结果:为什么不使用任何列表概念?这到底意味着什么?
Entered tuple : ('33', '77', '44', '77', '33')
Printing tuple in in (tuple element,frequency) format :
(('33', 2), ('77', 2), ('44', 1))