gpt4 book ai didi

python,将列表转换为类似的子列表

转载 作者:行者123 更新时间:2023-11-28 22:48:34 26 4
gpt4 key购买 nike

我想将名称列表转换为类似的子列表。例子

['yam-nb-109.0-8438773.i686.rpm', 'yam-nb-112.0-10561609.i686.rpm', 
'yam-ris-105.0-7269382.i686.rpm', 'yam-ris-106.0-7451269.i686.rpm',
'yam-ris-107.0-7899661.i686.rpm', 'yam-ris-112.0-10577466.i686.rpm',
'yam-logg-110.0-9833588.i686.rpm', 'yam-logg-111.0-10278753.i686.rpm',
'yam-logg-99.0-5275910.i686.rpm', 'yamboard-114.0-10902994.i686.rpm',
'yamboard-114.0-11436227.i686.rpm']

进入

[['yam-nb-109.0-8438773.i686.rpm', 'yam-nb-112.0-10561609.i686.rpm'], 
['yam-ris-105.0-7269382.i686.rpm', 'yam-ris-106.0-7451269.i686.rpm', 'yam-ris-107.0-7899661.i686.rpm', 'yam-ris-112.0-10577466.i686.rpm'],
['yam-logg-110.0-9833588.i686.rpm', 'yam-logg-111.0-10278753.i686.rpm', 'yam-logg-99.0-5275910.i686.rpm'],
['yamboard-114.0-10902994.i686.rpm', 'yamboard-114.0-11436227.i686.rpm']]

这里的任何建议都会有所帮助。

提前致谢...

最佳答案

使用 itertools.groupby :

>>> import itertools
>>>
>>> pkgs = [
... 'yam-nb-109.0-8438773.i686.rpm', 'yam-nb-112.0-10561609.i686.rpm',
... 'yam-ris-105.0-7269382.i686.rpm', 'yam-ris-106.0-7451269.i686.rpm',
... 'yam-ris-107.0-7899661.i686.rpm', 'yam-ris-112.0-10577466.i686.rpm',
... 'yam-logg-110.0-9833588.i686.rpm', 'yam-logg-111.0-10278753.i686.rpm',
... 'yam-logg-99.0-5275910.i686.rpm', 'yamboard-114.0-10902994.i686.rpm',
... 'yamboard-114.0-11436227.i686.rpm'
... ]
>>>
>>> pkg_name = lambda fn: fn.rsplit('-', 2)[0]
>>> [list(grp) for _, grp in itertools.groupby(pkgs, key=pkg_name)]
[['yam-nb-109.0-8438773.i686.rpm',
'yam-nb-112.0-10561609.i686.rpm'],
['yam-ris-105.0-7269382.i686.rpm',
'yam-ris-106.0-7451269.i686.rpm',
'yam-ris-107.0-7899661.i686.rpm',
'yam-ris-112.0-10577466.i686.rpm'],
['yam-logg-110.0-9833588.i686.rpm',
'yam-logg-111.0-10278753.i686.rpm',
'yam-logg-99.0-5275910.i686.rpm'],
['yamboard-114.0-10902994.i686.rpm',
'yamboard-114.0-11436227.i686.rpm']]

注意

以上代码假设

  • 您希望按包名对文件名进行分组
  • 文件名已排序
  • 包名相同后的版本号格式(package_name-version-version2.i686.rpm)

关于python,将列表转换为类似的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24970609/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com