首页 > 解决方案 > 如何显示元组列表并计算相同数量的元素

问题描述

输入 定义初始(daftar):

daftar = (

     "Michael","Viny","Aurelio","Michael",
     "Felix","Kevin","Vincen","Vincen","Michael")

inisial(daftar)

输出:

迈克尔

维尼

奥雷里奥

迈克尔2

菲利克斯

凯文

文森2

文森3

迈克尔3

标签: pythonlisttuplesnamedtuple

解决方案


您可以使用以下代码解决问题。

daftar = ("Michael", "Viny", "Aurelio", "Michael",
          "Felix", "Kevin", "Vincen", "Vincen", "Michael")

temp_dict = {}
for name in daftar:
    if temp_dict.get(name):
        temp_dict[name] += 1
    else:
        temp_dict[name] = 1

    if temp_dict[name] > 1:
        print('%s%d' % (name, temp_dict[name]))
    else:
        print(name)


推荐阅读