繁体   English   中英

如何根据for循环中给定列表的结果创建列表?

[英]How to create a list from results from a given list within a for loop?

我正在做 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]

这是怎么做的?

使用sum和生成器表达式很容易完成:

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

你可以简单地这样做:

def match_ends(words):
    count = 0

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

    return count

一个更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)

与之前的答案几乎相同,但 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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM