在Python中如何从string获取列表?

2024-05-31 23:18:53 发布

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

我从字典里得到一些值。但当我打印出来时,它会显示在底部,我需要将它们折叠成一个列表。你知道吗

我试了很多方法。同时列出理解。你知道吗

更新: 我的字典数据是:

Hours= [
   {'kota': 3, 'saat': '09:00'},
   {'kota': 3, 'saat': '09:20'},
   {'kota': 3, 'saat': '09:40'},
   {'kota': 3, 'saat': '10:00'},
   {'kota': 3, 'saat': '10:20'},
   {'kota': 3, 'saat': '10:40'},
   {'kota': 2, 'saat': '11:00'},
   {'kota': 2, 'saat': '11:20'},
   {'kota': 2, 'saat': '11:40'},

]

我从dic返回值:

for hour in hours:
a = hour.get("saat")  # From dicionary
print(a)

我的回报:

09:00
10:00
10:20

但我应该展示它们:

['09:00', '10:00', '10:20']

Tags: 数据方法infrom列表forget字典
3条回答

一行:

list(map(lambda x:x.get('saat'), Hours))

输出:

['09:00',
 '09:20',
 '09:40',
 '10:00',
 '10:20',
 '10:40',
 '11:00',
 '11:20',
 '11:40']

在开始处声明空列表。。遍历字典并将每个项附加到列表中。你知道吗

一旦整个迭代完成,打印循环外的列表。你知道吗

列表理解可能是最好的选择:

mylist = [hour.get("saat") for hour in Hours]

或者

mylist = [hour["saat"] for hour in Hours]

相关问题 更多 >