写一个声明而不调用任何函数?

时间:2017-02-09 15:12:06

标签: python function

为了在一行中优化代码,我试图在我的代码中编写一个确定的语句而不调用任何函数或方法。在我考虑这个问题时,我想知道在我的情况下这是否可行。我正在搜索关于此的一些信息,但它似乎很少,但在我目前的工作中,我必须能够保持代码完整,除了优化部分。 希望你能帮我一臂之力。欢迎任何帮助。

这是我目前的进展。

def count_chars(s):
'''(str) -> dict of {str: int}

    Return a dictionary where the keys are the characters in s and the  values
    are how many times those characters appear in s.

    >>> count_chars('abracadabra')
    {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}
    '''
    d = {}

    for c in s:
        if not (c in d):
            # This is the line it is assumed to be modified without calling function or method
        else:
            d[c] = d[c] + 1

    return d

1 个答案:

答案 0 :(得分:0)

如评论中所提到的,它如何隐含地使用函数,但我认为它可能是你正在寻找的那种东西?

s='abcab'
chars={}
for char in s:
    if char not in chars:
        chars[char]=0
    chars[char]+=1

结果

{'a': 2, 'b': 2, 'c': 1}