如何根据for-in列表中给定列表的结果创建列表

时间:2019-04-29 11:22:37

标签: python

我在做googles python类。并遇到了这个问题:

# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.

我尝试了不同的方法,但似乎无法使其正常工作。这就是我现在得到的:

def match_ends(words):
words=sorted(words, key=len)
for i in words:
    if len(i)<2:
        print(i)
        words=words[1:]
        print(words)
        for i in words:
            if i[0:2]==i[-2:]:
                x=[]
                x.append[i]

这是怎么做的?

4 个答案:

答案 0 :(得分:4)

使用sum和生成器表达式轻松完成:

def match_ends(words):
    return sum(len(word) >= 2 and word[0] == word[-1] for word in words)

答案 1 :(得分:2)

您可以简单地执行以下操作:

def match_ends(words):
    count = 0

    for word in words:
        if len(word) >= 2 and word[0] == word[-1]:
            count += 1

    return count

答案 2 :(得分:0)

更多的pythonic解决方案可能是

def func(s):
  return len(s) >= 2 and s[0] == s[-1]

str_list = ['applea', 'b', 'cardc']

filtered_list = [s for s in str_list if (len(s) >= 2 and s[0] == s[-1])]
# or 
filtered_list = list(filter(func, str_list))

count = len(filtered_list)

答案 3 :(得分:0)

与以前的答案几乎相同,但为lambda

match_ends = lambda ws: sum(1 for w in ws if len(w)>1 and w[0] == w[-1])

或“展开”表格

match_ends = lambda words: sum(1 for word in words if len(word)>1 and word[0] == word[-1])