2024-06-25 23:51:09 发布
网友
假设我有一个list,如下所示:
list
my_list = ["David Smith", "John Wilson", "Mike Davis", "Shawn Jones", "Shawn Gilmour", "David Berman"]
如果我想得到一个list,这样first和last的名字就分开了,这样我就可以count所有first名字的实例,我该怎么做呢?你知道吗
first
last
count
my_list = ["David Smith", "John Wilson", "Mike Davis", "Shawn Jones", "Shawn Gilmour", "David Berman"] new_list = [] for ele in my_list: for name in ele.split(): new_list.append(name)
输出:
print (new_list) ['David', 'Smith', 'John', 'Wilson', 'Mike', 'Davis', 'Shawn', 'Jones', 'Shawn', 'Gilmour', 'David', 'Berman']
可以将collections.Counter与生成器表达式一起使用,该表达式使用str.split提取名字:
collections.Counter
str.split
from collections import Counter Counter(name.split()[0] for name in my_list)
这将返回:
Counter({'David': 2, 'Shawn': 2, 'John': 1, 'Mike': 1})
使用defaultdict的解决方案。将名字存储为dict的键,每个名字加1。你知道吗
defaultdict
from collections import defaultdict result = defaultdict(int) my_list = ["David Smith", "John Wilson", "Mike Davis", "Shawn Jones", "Shawn Gilmour", "David Berman"] for first, last in map(lambda x: x.split(), my_list): result[first] += 1 David: 2 John: 1 Mike: 1 Shawn: 2
如果需要的话,您可以使用defaultdict(list)并附加issue result[first].append(last),它将把名字作为键,把姓氏列表作为它的值,如果出现用例,这些值可能会很有用。你知道吗
defaultdict(list)
result[first].append(last)
输出:
可以将
collections.Counter
与生成器表达式一起使用,该表达式使用str.split
提取名字:这将返回:
使用
defaultdict
的解决方案。将名字存储为dict的键,每个名字加1。你知道吗如果需要的话,您可以使用
defaultdict(list)
并附加issueresult[first].append(last)
,它将把名字作为键,把姓氏列表作为它的值,如果出现用例,这些值可能会很有用。你知道吗相关问题 更多 >
编程相关推荐