我想将名单列表转换为类似的子列表。例子
['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']]
这里的任何建议都会有所帮助。
提前致谢...
答案 0 :(得分:6)
>>> 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']]
注意强>
以上代码假设
答案 1 :(得分:-2)
没有图书馆:
sort(fromlist)
outlist=[["-"]]
for i in fromlist:
if i[:i.rfind("-")]!=outlist[-1][-1][:outlist[-1][-1].rfind("-")]:
outlist.append([])
outlist[-1].append(i)