练习python:如何对列表中的元素进行分组?

2024-09-28 03:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着解决下面的练习,不使用datetime

练习:

Given a list of int, such that the First three int represent a date, the second three elementi represent a date etc..modify lst by grouping every triple in One string with the numbers separeted by "/".

示例:

lst = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000]
groupd(lst)
lst
['1/2/2013', '23/9/2011', '10/11/2000']

我的尝试:

lst = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000]. 
stri = str(lst).   

def groupd(lst):. 
cont = 1. 
a = (stri.replace(',', '/')).  
    for x in lst:. 
        if len[x]>2:.                
            lst.insert(lst[0],a )].   
                print(a).          
print(groupd(lst)). 

PS:对不起我的英语!!谢谢大家


Tags: oftheindatetimedatebygivenlist
3条回答

这更像是一种函数方法,其中答案是通过递归函数传递的

lst1 = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000] 
lst2 = []
lst3 = [1,2, 2015]
lst4 = [1,2]
lst5 = [1]
lst6 = [1,2,2013, 23, 9]

def groupToDate(lst, acc): 
    if len(lst) < 3:
        return acc
    else:
        # take first elements in list
        day = lst[0]
        month = lst[1]
        year = lst[2]
        acc.append(str(day) + '/' + str(month) + '/' + str(year))
        return groupToDate(lst[3:len(lst)], acc)


print(groupToDate(lst1, []))
print(groupToDate(lst2, []))
print(groupToDate(lst3, []))
print(groupToDate(lst4, []))
print(groupToDate(lst5, []))
print(groupToDate(lst6, []))

如果您不想使用列表理解或groupby,这也是解决此类问题的基本方法

可以使用zip创建元组,然后将它们格式化为字符串:

>>> ['%d/%d/%d' % parts for parts in zip(lst[::3], lst[1::3], lst[2::3])]
['1/2/2013', '23/9/2011', '10/11/2000']

从偏移量(第一个参数到切片)开始,同时跳过项目(第三个参数到切片)允许窗口行为

更一般地说:

>>> N = 3
>>> ['/'.join(['%d'] * N) % parts for parts in zip(*[lst[start::N] for start in range(N)])]
['1/2/2013', '23/9/2011', '10/11/2000']

您可以使用itertools中的groupby按索引对列表进行分组:

from itertools import groupby
['/'.join(str(i[1]) for i in g) for _, g in groupby(enumerate(lst), key = lambda x: x[0]/3)]

# ['1/2/2013', '23/9/2011', '10/11/2000']

相关问题 更多 >

    热门问题