计算 input_list 中以‘S’开头的单词数
Count the number of words that start with ‘S’ in input_list
我想通过仅使用 map 函数和 lambda 函数来计算单词数
这是我写的代码
input_list = ['San Jose', 'San Francisco', 'Santa Fe', 'Houston']
len(list(map(lambda word:word if word[0]=="S",input_list)))
然而,这会抛出这样的错误
File "/code/source.py3", line 5
count = len(list(map(lambda word:word if word[0]=="S",input_list)))
^
SyntaxError: invalid syntax
如果您坚持使用 map()
,那么使用 sum()
可能有效:
input_list = ['San Jose', 'San Francisco', 'Santa Fe', 'Houston']
count = sum(map(lambda word:word[0]=="S", input_list))
请注意,word[0]=="S"
的计算结果为 True
或 False
,当与 sum()
一起使用时,将分别转换为 1
或 0
.
len([x for x in input_list if x.startswith('S')])
或者你可以这样做
sum(map(lambda x:x.startswith("S"), input_list))
我想通过仅使用 map 函数和 lambda 函数来计算单词数
这是我写的代码
input_list = ['San Jose', 'San Francisco', 'Santa Fe', 'Houston']
len(list(map(lambda word:word if word[0]=="S",input_list)))
然而,这会抛出这样的错误
File "/code/source.py3", line 5
count = len(list(map(lambda word:word if word[0]=="S",input_list)))
^
SyntaxError: invalid syntax
如果您坚持使用 map()
,那么使用 sum()
可能有效:
input_list = ['San Jose', 'San Francisco', 'Santa Fe', 'Houston']
count = sum(map(lambda word:word[0]=="S", input_list))
请注意,word[0]=="S"
的计算结果为 True
或 False
,当与 sum()
一起使用时,将分别转换为 1
或 0
.
len([x for x in input_list if x.startswith('S')])
或者你可以这样做
sum(map(lambda x:x.startswith("S"), input_list))