python - Python按字母顺序将列表转换为字典
问题描述
例如如何转换列表
['and', 'power', 'car', 'abc', 'pen', 'doctor', 'pig']
按字母顺序到字典
{A 1: 'abc', A 2: 'and', C 1: 'car', D 1: 'doctor', P 1: 'pen', P 2: 'pig', P 3: 'power'}
解决方案
字典插入现在保留顺序,但如果你使用的是旧版本的 Python,你会想要使用 OrderedDict。
lst = ['and', 'power', 'car', 'abc', 'pen', 'doctor', 'pig']
lst.sort() # in-place
d = {}
i = 1
for item in lst:
if item[0].upper() in [k[0] for k in d.keys()]:
i += 1
else:
i = 1
d[item[0].upper() + ' ' + str(i)] = item
结果:
In [92]: d
Out[92]:
{'A 1': 'abc',
'A 2': 'and',
'C 1': 'car',
'D 1': 'doctor',
'P 1': 'pen',
'P 2': 'pig',
'P 3': 'power'}
推荐阅读
- apache-kafka - Scrapy-cluster 回调请求不起作用,卡在处理元直通中间件
- postgresql - 如何将镶木地板文件从 s3 导入到 postgresql rds
- php - 使用 'for' PHP 计算单词
- python - Pandas 按二和一变量分组
- python - GCF 的软件包是如何获得的?
- java - 什么错误“mysqlinsert E/MultiWindowProxy:getServiceInstance 失败!” 方法?
- typescript - Typescript函数数组类型检查
- xamarin.forms - Xamarin Forms:如何在 Xamarin Forms 中创建 Epub 查看器?
- geospatial - Snowflake DB:如何在 Snowflake 中绘制地理空间球体特征?
- python-3.x - 使用 imshow 函数显示图像时出错