作者Hsins (迅雷不及掩耳盗铃)
看板Python
标题Re: [问题] 列表中依据元素分组
时间Wed Dec 18 17:03:01 2019
※ 引述《radiant77 (七七)》之铭言:
: 有一个列表,长度非固定,其中有A、B、C、D、NAV等字
: 希望依据总分放到不同的list中,只看英文字母,前面的数字不算分
: A = 1分
: B = 2分
: C = 2分
: D = 3分
: NAV或0分的一组
: 例如:'7A-1A'有两个A,就是1+1=2分,'1C', '3B'也都是2分
: '1A-7C-3A',就是1+2+1=4分,'28A-7A-3A-1A'是1+1+1+1=4分
: 列表如下:
: list = ['1A', '7A', '7A-1A', '1A-7A', '1C', '3D', '3B', '3A-7B', '1A-28A-3A',
: '20A-7A-3A', '28A-7A-3A-1A', '7A-3A-1A-28A', '1A-7C-3A', '7B-3A-1A', '3C-7A',
: '7B-3NAV', '3B-7NAV', '20-7', '7']
: 依照总分排序後的新列表如下:
: 1分 : list_1 = ['1A', '7A']
: 2分 : list_2 = ['7A-1A', '1A-7A', '1C', '3B']
: 3分 : list_3 = ['3D', '3A-7B', '1A-28A-3A', '20A-7A-3A', '3C-7A']
: 4分 : list_4 = ['28A-7A-3A-1A', '7A-3A-1A-28A', '1A-7C-3A', '7B-3A-1A']
: 其他: list_NAV = ['7B-3NAV', '3B-7NAV', '20-7', '7']
: ----------------------------------------
: 我之前只有分到2分,用的方法比较简单,无法对应更多的分数
: 希望能直接依据总分来分组,以後要计算5.6.7分的话可以方便新增
: 以下是我之前用的方法:
: 1分 list_1 = [i for i in list if i.count('A') and not i.count('-')]
: 2分 list_2 = [i for i in list if i.count('A') <> 1 and not i.count('-') == 2]
: 还请前辈看看,谢谢!
如果是我会这样做:
```python
# import defaultdict for dictionary appending
from collections import defaultdict
result = defaultdict(list)
# define char-score pair and scores calculating function
char_score = {'A': 1, 'B': 2, 'C': 2, 'D': 3}
calculate_score = lambda string: sum([string.count(k) * v for k, v in
char_score.items()])
# traverse and create score_list
words = ['1A', '7A', '7A-1A', '1A-7A', '1C', '3D', '3B', '3A-7B',
'1A-28A-3A', '20A-7A-3A', '28A-7A-3A-1A', '7A-3A-1A-28A', '1A-7C-3A',
'7B-3A-1A', '3C-7A', '7B-3NAV', '3B-7NAV', '20-7', '7']
for word in words:
if 'NAV' in word or calculate_score(word) == 0:
result['NAV'].append(word)
else:
result[calculate_score(word)].append(word)
```
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.112.247.1 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1576659783.A.1DA.html
1F:推 cuteSquirrel: 推 12/18 18:50