列表练习 – 根据条件返回字符串数量

huangapple go评论70阅读模式
英文:

List exercise - Return the number of strings based on a condition

问题

这是你的代码翻译部分:

def string_num(items): 
    for a in items: 
        len(a) >= 3 and (a[0] == a[-1]) 
    return items.count(a) 
print(string_num(['abc','xyz','aba','1221']))

如果你有任何其他问题或需要进一步的帮助,请告诉我。

英文:

I'm a newbie in the Python world. I'm still struggling with some of the basic concepts of Python.

Question: **Write a program that counts the number of string from a given list of strings. This string is 2 characters or more and the first and last characters are the same **

As the question mentioned in the title, this was my approach:

def string_num(items): 
    for a in items: 
        len(a) >= 3 and (a[0] == a[-1]) 
    return items.count(a) 
print(string_num(['abc','xyz','aba','1221'])) 

I assumed that the .count() function cannot be used here to count string in a list under a specific condition. I have been looking around but I still have not seen any explanation. Could someone help me explain what's wrong with this code, or what the .count() function does exactly that it cannot be used here?

Appreciate all the help!

答案1

得分: 0

你的心理模型似乎与Python的实际运行方式相去甚远。

for循环只是简单地遍历一个表达式,该表达式不做任何事情。(它在每次迭代时产生TrueFalse,但你对该值不做任何操作。)

最后,items.count(a) 计算 a(它将是循环中最后一次迭代的 a 的值,该值仍然在循环结束后可用,即 '1221')在 items 中出现了多少次。

我猜你可能想要类似这样的东西

def string_num(items): 
    return len([a for a in items if len(a) >= 3 and a[0] == a[-1]])

可以更详细地写成

def string_num(items): 
    count = 0
    for a in items:
        if len(a) >= 3 and a[0] == a[-1]:
            count += 1
    return count

正如Unmitigated所指出的,甚至可以在这里使用 sum,因为True在数值上等于1,而False为0。

def string_num(items): 
    return sum(len(a) >= 3 and a[0] == a[-1] for a in items)
英文:

Your mental model seems to be pretty far off from how Python actually works.

The for loop simply loops over an expression which ... does nothing. (It produces True or False in each iteration, but you don't do anything with that value.)

Finally, items.count(a) counts how many times a (which will be the value of a from the last iteration in the loop, which is still available after the loop has finished, i.e. '1221') occurs in items.

I guess you were looking for something like

def string_num(items): 
    return len([a for a in items if len(a) >= 3 and a[0] == a[-1]])

which can be written less succinctly as

def string_num(items): 
    count = 0
    for a in items:
        if len(a) >= 3 and a[0] == a[-1]:
            count += 1
    return count

As remarked by Unmitigated, you could even use sum here, since True is numerically equal to 1 and False is 0.

def string_num(items): 
    return sum(len(a) >= 3 and a[0] == a[-1] for a in items)

答案2

得分: 0

.count() 函数用于计算数组中某个值的出现次数,示例可参见这里。如果你想要获取列表中元素的数量,可以使用你已经用于字符串长度的 len() 函数。

另外,你提供的方法不会生效,因为它实际上没有计算满足条件的字符串的数量。

我建议使用以下方式之一:

def string_num(items):
    item_count = 0
    for a in items: 
        if len(a) >= 3 and a[0] == a[-1]:
            item_count += 1
 
    return item_count
 
print(string_num(['abc','xyz','aba','1221'])) 

或者你可以使用列表推导式,这样会更为简洁:

def string_num(items):
    return len([v for v in items if len(v) >= 3 and v[0] == v[-1]])

print(string_num(['abc','xyz','aba','1221']))

<details>
<summary>英文:</summary>

The `.count()` function counts the occurences of a value in an array, see the example [here][1]. If you want to get the number of elements in a list, use the `len()` function you already used for the string length.

Also, this will not work, since you don&#39;t actually count the number of strings that fulfill this condition.

I would do something like this:

```py
def string_num(items):
    item_count = 0
    for a in items: 
        if len(a) &gt;= 3 and a[0] == a[-1]:
            item_count += 1
 
    return item_count
 
print(string_num([&#39;abc&#39;,&#39;xyz&#39;,&#39;aba&#39;,&#39;1221&#39;])) 

Or you could do it with list comprehension like this, which is a bit more concise:

def string_num(items):
    return len([v for v in items if len(v) &gt;= 3 and v[0] == v[-1]])

print(string_num([&#39;abc&#39;,&#39;xyz&#39;,&#39;aba&#39;,&#39;1221&#39;]))

huangapple
  • 本文由 发表于 2023年3月20日 23:43:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75792392.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定