对于循环仅迭代列表中的最后一个元素

时间:2019-11-18 01:00:08

标签: python loops

list =[]
number = int(input("how many names do you want in a list: "))
for i in range(0,number):    
    string_list = (input("enter desired names:"))
    list.append(string_list)

all_freq = {}
for i in string_list:
    if i in all_freq: 
        all_freq[i] += 1
    else: 
        all_freq[i] = 1
print(list)
print ("Count of all characters in names is :\n "
                                        +  str(all_freq))

2 个答案:

答案 0 :(得分:0)

尝试

list =[]
number = int(input("how many names do you want in a list: "))
for i in range(0,number):    
    string_list = (input("enter desired names:"))
    list.append(string_list)

all_freq = {}
for name in list:
    for c in name:
        if c in all_freq: 
            all_freq[c] += 1
        else: 
            all_freq[c] = 1

print ("Count of all characters in names is :\n "
                                        +  str(all_freq))

答案 1 :(得分:0)

如果我理解正确,那么您希望将所有名称的每个字符的数量相结合。

您可以使用set()获取唯一字符,并使用str.count()对其计数

    string_list = ""
    number = int(input("how many names do you want in a list: "))
    for i in range(number):
        string_list += input("enter desired name:")
    unique_chars = set(string_list)  # getting all unique characters 
    all_freq = {}
    for i in unique_chars:
        all_freq[i] = string_list.count(i)  # returns the count of the character

    print("Count of all characters in names is :\n "
          + str(all_freq))