2024-04-26 17:58:59 发布
网友
import string a = "I'm not gonna post my homework as question on OS again, I'm not gonna..." count = lambda l1, l2: len(list(filter(lambda c: c in l2, l1))) a_chars = count(a, string.ascii_letters) a_punct = count(a, string.punctuation)
count_chars = ".arPZ" string = "Phillip S. is doing a really good job." counts = tuple(string.count(c) for c in count_chars) print counts
(2, 2, 1, 1, 0)
对于更精简/更快的版本,还有
count=lambda l1,l2:sum([1表示l1中的x,如果x表示l2中的x])
例如:
count = lambda l1,l2: sum([1 for x in l1 if x in l2]) In [11]: s = 'abcd!!!' In [12]: count(s,set(string.punctuation)) Out[12]: 3
使用一套应该会让你的速度有所提高。
另外,取决于字符串的大小,我认为您应该通过过滤器获得内存优势。
对于更精简/更快的版本,还有
count=lambda l1,l2:sum([1表示l1中的x,如果x表示l2中的x])
例如:
使用一套应该会让你的速度有所提高。
另外,取决于字符串的大小,我认为您应该通过过滤器获得内存优势。
相关问题 更多 >
编程相关推荐