给出python中的字典列表
my_list=[{'id':0,'name':'cube0_cluster0','member_ids': [429, 432, 435]},
{'id': 1,'name': 'cube0_cluster1','member_ids': [0, 4, 5]},
{'id':0,'name':'cube1_cluster1','member_ids': [4, 706, 800]}]
我要为member_ids
打印所有cube{ }_cluster1
我的预期输出是打印[0,4,5,706,800]
任何帮助将不胜感激
我尝试过
for k in my_list:
for j in range(len(my_list)):
if k['name']=='cube{}_cluster1'.format(j):
print(k['member_ids'])
但是我得到两个单独的输出,分别为[0,4,5]
和[4,706,800]
答案 0 :(得分:1)
尝试这个。
import re
member_ids = []
for di in my_list:
if re.match('cube\d_cluster1', di['name']):
member_ids += di['member_ids']
print(member_ids)
答案 1 :(得分:1)
您还可以使用列表推导。
my_list=[{'id':0,'name':'cube0_cluster0','member_ids': [429, 432, 435]},
{'id': 1,'name': 'cube0_cluster1','member_ids': [0, 4, 5]},
{'id':0,'name':'cube1_cluster1','member_ids': [4, 706, 800]}]
res = [j for i in my_list for j in i['member_ids'] if "cluster1" in i["name"]]
print (res) # return list
print (set(res)) # to return distinct data
# Result
# [0, 4, 5, 4, 706, 800]
# {0, 800, 706, 4, 5}
我希望这对您有所帮助!