簡體   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