gpt4 book ai didi

python - 通过 Python 列表过滤以查找常见元素

转载 作者:行者123 更新时间:2023-11-28 21:11:36 24 4
gpt4 key购买 nike

我正在尝试找到一种有效的方法来遍历列表中的元素,并将常见元素组合到另一个列表 grouplist 中。

例子

In[]: grouplist = []

In[]: filelist
Out[]:['C:\\West-California-North-10.xlsx',
'C:\\West-California-North-5.xlsx',
'C:\\West-California-East-1.xlsx',
'C:\\West-California-South-1.xlsx',
'C:\\South-California-North-5.xlsx',
'C:\\West-California-South-3.xlsx']

我想找到一组具有不同整数的常见模式。所以在这种情况下,

第一次迭代grouplist =

 C:\\West-California-North-10.xlsx
C:\\West-California-North-5.xlsx

第二次迭代 =

 C:\\West-California-East-1.xlsx

第三次迭代=

 C:\\West-California-South-1.xlsx
C:\\West-California-South-3.xlsx

最佳答案

itertools.groupby 是你的 friend :

from itertools import groupby


filelist = [
'C:\\West-California-North-10.xlsx',
'C:\\West-California-North-5.xlsx',
'C:\\West-California-East-1.xlsx',
'C:\\West-California-South-1.xlsx',
'C:\\South-California-North-5.xlsx',
'C:\\West-California-South-3.xlsx']

key_fn = lambda s: s.rsplit('-',1)[0]

# before grouping, list has to be sorted
filelist = sorted(filelist, key=key_fn)

# usually use the same key_fn for grouping as was used for sorting
for key, grouped_file_names in groupby(filelist, key=key_fn):
# groupby returns an iterator of tuples
# the first element of the tuple is the grouped key value
# the second element is a generator of the items that matched that key
# (YOU MUST CONSUME THIS GENERATOR BEFORE MOVING ON TO THE NEXT KEY)
print '\n'.join(list(grouped_file_names))
print

打印

C:\South-California-North-5.xlsx

C:\West-California-East-1.xlsx

C:\West-California-North-10.xlsx
C:\West-California-North-5.xlsx

C:\West-California-South-1.xlsx
C:\West-California-South-3.xlsx

关于python - 通过 Python 列表过滤以查找常见元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35089586/

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