python - 将列表转换为字典,其中列表值为字典键和值
问题描述
我有一个包含长字符串的列表,一个数字,然后是一个“句子”,比如说。我想知道是否有办法把它变成字典,数字是值
mylist = ['8 red cars', '3 blue cars', '11 black cars']
那是我的清单,我希望字典是:
{
'red cars': 8
'blue cars': 3
'black cars': 11
}
解决方案
我相信有更好的方法,但下面的代码适用于您的示例。
mylist = ['8 red cars', '3 blue cars', '11 black cars']
car_dict = {}
for item in mylist:
number = [int(s) for s in item.split() if s.isdigit()][0]
words = [str(s) for s in item.split() if s.isalpha()]
car_dict[number] = ' '.join(words)
print(car_dict)
推荐阅读
- postgresql - Pgbouncer - 管理动态数据库设置
- c - OpenSSL 调试 - 如何在 openssl 中转储中间 ASN.1?
- java - 如何强制用户使用前置摄像头?
- python - 在python中对相似值进行分组和求和
- python-3.x - Python - 跳过 *args 和 **kwargs
- ios - 如何通过将其存储在 [NSKeyedArchiver archivedDataWithRootObject: 中来获取具有相同地址的数组?
- python - Django:图片未在 HTML 模板中加载
- php - 在sql中动态创建的多个单选按钮
- asp.net - 更换 PC 时的无限循环/重定向简单的 ASP.NET OWIN Azure AD Web 解决方案
- java - 是什么让 Web 容器首先在 Web 应用程序中加载 web.xml?