如何将返回列表的布局改进为[a = 0,b = 0,...]?

时间:2017-10-09 16:53:37

标签: python-3.x

要点:

下面的函数计算字符串中的字母并将它们放在一个列表中并返回列表。

问题:

以下功能返回的列表看起来并不优雅。

string = "Hello, world!"
lijst = []
string = string.lower()

def countAlphabeth( string ):
    for i in range( 0, 26 ):
        x = chr(ord( "a" ) + i )
        string.count( x )
        lijst.append( str( x + ' =' ) )
        lijst.append(string.count( x ) )
    return lijst

lijst = countAlphabeth( string )
print( lijst )

这是打印后列表显示的方式:

['a =', 0, 'b =', 0, 'c =', 0, 'd =', 1, 'e =', 1, 'f =', 0, 'g =', 0, 'h =', 
  1, 'i =', 0, 'j =', 0, 'k =', 0, 'l =', 3, 'm =', 0, 'n =', 0, 'o =', 2, 
 'p =', 0, 'q =', 0, 'r =', 1, 's =', 0, 't =', 0, 'u =', 0, 'v =', 0, 'w =', 
  1, 'x =', 0, 'y =', 0, 'z =',0]

期望的结果:

我应该做些什么改变才能得到如下所示的结果?

[a = 0, b = 0, c = 0, d = 1, e = 1, f = 0, g = 0, h = 1, i = 0, j = 0, k = 0,
 l = 3, m = 0, n = 0, o = 2, p = 0, q = 0, r = 1, s = 0, t = 0, u = 0, v = 0,
 w = 1, x = 0, y = 0, z = 0]

3 个答案:

答案 0 :(得分:1)

您是否考虑过使用Counter

from collections import Counter
from string import ascii_lowercase

def print_count(s : str):
    c = Counter(s.lower())
    for letter in ascii_lowercase:
        print('{} = {}'.format(letter, c[letter]))

print_count('Hello, world!')

打印

a = 0
b = 0
c = 0
d = 1
e = 1
f = 0
g = 0
h = 1
i = 0
j = 0
k = 0
l = 3
m = 0
n = 0
o = 2
p = 0
q = 0
r = 1
s = 0
t = 0
u = 0
v = 0
w = 1
x = 0
y = 0
z = 0

答案 1 :(得分:0)

您以某种奇怪的方式使用列表。你真正想要的是一本字典。我做这样的事情:

class Freq:
    def __init__(self, string):
        self.dijct = {}
        for i in range( 0, 26 ):
            x = chr(ord( "a" ) + i )
            string.count( x )
            self.dijct[x] = string.count(x)

    def __str__(self):
        printString = "["

        for (letter, frequency) in self.dijct.items():
            printString += "{} = {}, ".format(letter, frequency)

        printString = printString[:-2] # remove trailing comma and space
        printString += "]"
        return printString

string = "Hello, world!"
string = string.lower()

print(Freq(string))

输出:

[a = 0, b = 0, c = 0, d = 1, e = 1, f = 0, g = 0, h = 1, i = 0, j = 0, k = 0, l = 3, m = 0, n = 0, o = 2, p = 0, q = 0, r = 1, s = 0, t = 0, u = 0, v = 0, w = 1, x = 0, y = 0, z = 0, ]

有可能编写自己的__str__函数并使用python的列表类来使用它,但我认为你提供自己的类来存储频率要好得多分配,这样你就可以直接提供自己的打印功能。

答案 2 :(得分:0)

你可以使用计数器。记下您想要的值列表。

from collections import Counter

def data_list(str_data):
    lst = list()
    if not isinstance(str_data, str):
        return lst
    resp = Counter(str_data.lower())
    for ascii in range(97, 123):
        letter = chr(ascii)
        lst.append('{} = {}'.format(letter, resp.get(letter, 0)))
    return lst

print(data_list('Hello, world!'))

输出:

['a = 0', 'b = 0', 'c = 0', 'd = 1', 'e = 1', 'f = 0', 'g = 0', 'h = 1', 'i = 0', 'j = 0', 'k = 0', 'l = 3', 'm = 0', 'n = 0', 'o = 2', 'p = 0', 'q = 0', 'r = 1', 's = 0', 't = 0', 'u = 0', 'v = 0', 'w = 1', 'x = 0', 'y = 0', 'z = 0']