【问题标题】:Find the frequency of every unique elements in tuple(without using any list concept) and concatenate with its word查找元组中每个唯一元素的频率(不使用任何列表概念)并与其单词连接
【发布时间】:2020-03-11 09:38:48
【问题描述】:

我尝试了以下代码:

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))

【问题讨论】:

  • 你可以使用Counter(tup)(我确定这是重复的..)
  • tuple(Counter(('1', '2', '3', '4', '1')).items())
  • 谢谢@Sayse。得到了预期的:)
  • 为什么要“不使用任何列表概念”?那究竟是什么意思?

标签: python tuples concatenation word-frequency


【解决方案1】:

1) 我已经在我的代码中导入了集合模块。

from collections import Counter

2) 循环中的计数器(tup)。

for x in Counter(tup) :

输出

Entered tuple : ('33', '77', '44', '77', '33')
Printing tuple in in (tuple element,frequency) format  : 
(('33', 2), ('77', 2), ('44', 1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2010-11-16
    • 1970-01-01
    相关资源
    最近更新 更多