返回由字符串元素及其长度组成的对列表 - Python

时间:2014-08-21 02:44:15

标签: python python-2.7

我无法获得结果以在对列表中显示信息。

def add_sizes(strings):
    """Return the list of pairs consisting of the elements of strings together
    with their sizes.

    add_sizes(list<string>) -> list<(string, integer)>
    """
        c = []
        for i in strings:
            c.append(i)
            c.append(len(i))
        return c

我得到的结果是:

>>> add_sizes(['sun', 'a']) ['sun', 3, 'a', 1]

我之后是:

>>> add_sizes(['sun', 'a']) [('sun', 3), ('a', 1)]

2 个答案:

答案 0 :(得分:1)

您需要附加元组而不是追加两次:

c.append((i, len(i)))

或者,更pythonic的方法是使用列表理解:

def add_sizes(strings):
    return [(i, len(i)) for i in strings]

答案 1 :(得分:0)

def add_sizes(strings):
    """Return the list of pairs consisting of the elements of strings together
    with their sizes.

    add_sizes(list<string>) -> list<(string, integer)>
    """
        c = []
        for i in strings:
            c.append((i,len(i))
        return c

但是,我认为最好使用字典

def add_sizes(strings): return {i:len(i) for i in strings}