如何将列表中的元素拆分为它们自己的元素?

2024-06-25 23:51:09 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个list,如下所示:

my_list = ["David Smith", "John Wilson", "Mike Davis", "Shawn Jones", 
            "Shawn Gilmour", "David Berman"]

如果我想得到一个list,这样firstlast的名字就分开了,这样我就可以count所有first名字的实例,我该怎么做呢?你知道吗


Tags: my名字johnlistfirstlastmikedavid
3条回答
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提取名字:

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。你知道吗

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),它将把名字作为键,把姓氏列表作为它的值,如果出现用例,这些值可能会很有用。你知道吗

相关问题 更多 >