Python计算列表的值,并将它们放入没有库的有序列表中

2024-09-30 20:20:10 发布

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

假设我有一张清单

List = ['Antonia', 'Sara', 'Nick', 'Deppy', 'Antonia', 'Deppy', 'Antonia']

我想数一数

尼克:1

莎拉:1

德比:2

安东尼娅:3

有没有办法制作一个新的列表,它们的顺序如下:

New_List = ['Antonia', 'Deppy', 'Sara', 'Nick']

?


Tags: 列表new顺序nicklist办法saraantonia
1条回答
网友
1楼 · 发布于 2024-09-30 20:20:10

有很多方法可以实现你的目标。以下是一个简单的方法:

the_list = ['Antonia', 'Sara', 'Nick', 'Deppy', 'Antonia', 'Deppy', 'Antonia']

# count unique item in the list 'the_list'
for item in set(the_list):
    print(item, ':', the_list.count(item))

# an ordered new list containing unique item of 'the_list'
new_list = sorted([item for item in set(the_list)])
print(new_list)

Outputs:

Nick : 1
Antonia : 3
Sara : 1
Deppy : 2

['Antonia', 'Deppy', 'Nick', 'Sara']

相关问题 更多 >