如何遍历列表中的每个字符串?

时间:2015-09-21 05:50:32

标签: python list function loops append

我试过这段代码,但它只对列表中的第一个字符串执行函数:

返回给定字符串列表

的第一个和最后两个字符
def both_ends(list):
    finalList = []
    for s in list:
        if s > 2:
            return s[0] + s[1] + s[-2] + s[-1]
        else:
            return s

    finalList.append(s)
    return finalList

list = ('apple', 'pizza', 'x', 'joke')
print both_ends(string)

如何让这个函数运行列表中的所有字符串?

3 个答案:

答案 0 :(得分:3)

是的,那是因为你直接返回结果,所以它会在你完成第一个字符串后返回。相反,您应该将结果放在您创建的finalList中并在结尾处返回结果。

还有其他一些事情 -

  1. 正如在另一个答案中所说,你想检查字符串的长度。

  2. 字符串的长度应大于4,否则,最终会多次添加一些字符。

  3. 不要将list之类的名称用于变量,它最终会影响内置函数,因此在此之后您将无法使用list()创建列表。

  4. 最后一个问题是,您应该使用列表调用函数,而不是string

  5. 示例 -

    def both_ends(list):
        finalList = []
        for s in list:
            if len(s) > 4:
                finalList.append(s[:2] + s[-2:])
            else:
                finalList.append(s)
        return finalList
    

    更简单的方法 -

    def both_ends(s):
        return s[:2] + s[-2:] if len(s) > 4 else s
    
    lst = ('apple', 'pizza', 'x', 'joke')
    print map(both_ends, lst)          #You would need `list(map(...))` for Python 3.x
    

    演示 -

    >>> def both_ends(s):
    ...     return s[:2] + s[-2:] if len(s) > 4 else s
    ... 
    >>> lst = ('apple', 'pizza', 'x', 'joke')
    >>> print map(both_ends, lst) 
    ['aple', 'piza', 'x', 'joke']
    

    甚至是列表理解,虽然对我来说它的可读性稍差 -

    [s[:2] + s[-2:] if len(s) > 4 else s for s in lst]
    

    演示 -

    >>> lst = ('apple', 'pizza', 'x', 'joke')
    >>> [s[:2] + s[-2:] if len(s) > 4 else s for s in lst]
    ['aple', 'piza', 'x', 'joke']
    

答案 1 :(得分:1)

您想要检查字符串的长度,而不是字符串本身。因此,做s > 2并不能做你想做的事情:

def both_ends(lst):
    finalList = []
    for s in lst:
        if len(s) > 2:
            finalList.append(s[0] + s[1] + s[-2] + s[-1])
        else:
            finalList.append(s)
    return finalList

lst = ['apple', 'pizza', 'x', 'joke']
print both_ends(lst)

很少有其他事情:

  • 不要命名变量list。它将覆盖内置类型。
  • 你有一个元组(..., ...)。列表带有方括号。
  • 您有print both_ends(string),而不是列入您的列表。

最后,您可以缩短代码:

print [s[:2] + s[-2:] if len(s) > 2 else s for s in lst]

答案 2 :(得分:0)

有些问题引起了我的注意。

  • 您将在第一次迭代后立即返回,因此只获取第一个元素。
  • 我想你要比较长度是否大于4,len(s)>4
  • 也是如此
  • 不要将数据类型名称用作变量名称。使用已使用的list,请勿使用它。

不要立即返回,而是附加到列表中。

 def both_ends(lst):
    finalList = []
    for s in lst:
        if len(s) > 4:
           finalList.append( s[0] + s[1] + s[-2] + s[-1])
        else:
           finalList.append(s)


    return finalList

lst = ['apple', 'pizza', 'x', 'joke']
print both_ends(lst)

输出:

['aple', 'piza', 'x', 'joke']
相关问题