保留 Python 列表中的特定范围的项。

huangapple go评论66阅读模式
英文:

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'}]

huangapple
  • 本文由 发表于 2023年6月16日 02:58:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484735.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定