英文:
Keep a specific range of items in a list python
问题
我有以下的Python嵌套列表(只是一个示例):
[{'512', '530', '788'}, {'112', '401', '276', '280', '787', '555'}, {'284', '041', 'V64.0', 'E8798', 'V15.8', '205'}]
我希望得到以下输出:
[{'512', '530', '788'}, {'112', '401', '276'}, {'284', '041', 'V64.0'}]
说明:我只想保留每个列表中特定数量的项。
英文:
I have the following nested list in python (just an example):
[{'512', '530', '788'}, {'112', '401', '276', '280', '787', '555'}, {'284', '041', 'V64.0', 'E8798', 'V15.8', '205'}]
I desire the following output:
[{'512', '530', '788'}, {'112', '401', '276'}, {'284', '041', 'V64.0'}]
Explanation: I just want to keep a specific number of items per list.
答案1
得分: 2
另一种解决方案(注意:列表中的项目是集合,因此无序。如果顺序很重要,请选择元组或列表):
out = [{a, b, c} for a, b, c, *_ in lst]
print(out)
打印:
[{'512', '530', '788'}, {'280', '555', '276'}, {'041', '284', '205'}]
英文:
Another solution (note: the items in the list are sets, so unordered. If the order is important chose tuple or list):
out = [{a, b, c} for a, b, c, *_ in lst]
print(out)
Prints:
[{'512', '530', '788'}, {'280', '555', '276'}, {'041', '284', '205'}]
答案2
得分: 0
[
{'512', '530', '788'},
{'280', '401', '787'},
{'205', 'V15.8', 'V64.0'}
]
英文:
lst = [{'512', '530', '788'}, {'112', '401', '276', '280', '787', '555'}, {'284', '041', 'V64.0', 'E8798', 'V15.8', '205'}]
[set(tuple(x)[:3]) for x in lst]
#or
[set(list(x)[:3]) for x in lst]
[{'512', '530', '788'}, {'280', '401', '787'}, {'205', 'V15.8', 'V64.0'}]
This could also do the job if we are looking for another method. It avoids turning the set into a list or tuple.
lst = [{'512', '530', '788'}, {'112', '401', '276', '280', '787', '555'}, {'284', '041', 'V64.0', 'E8798', 'V15.8', '205'}]
[{e for (e, _) in zip(x, range(3))} for x in lst] # here range specifies the number of elements needed.
[{'512', '530', '788'}, {'280', '401', '787'}, {'205', 'V15.8', 'V64.0'}]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论