练习python:如何将列表中的元素分组?

练习python:如何将列表中的元素分组?,python,list,Python,List,我试图解决以下练习,但没有使用datetime 练习: 给定一个int列表,前三个int代表一个日期, 第二个三个元素I表示日期等。通过分组修改lst 一个字符串中的每个三元组,数字以“/”分隔 例如: 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,

我试图解决以下练习,但没有使用datetime

练习:

给定一个int列表,前三个int代表一个日期, 第二个三个元素I表示日期等。通过分组修改lst 一个字符串中的每个三元组,数字以“/”分隔

例如:

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:对不起我的英语!!谢谢大家!

您可以使用
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']

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

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, []))
lst1=[1,2,2013,23,9,2011,10,11,2000]
lst2=[]
lst3=[1,22015]
lst4=[1,2]
lst5=[1]
lst6=[1,22013,23,9]
def组日期(lst,acc):
如果len(lst)<3:
返回acc
其他:
#获取列表中的第一个元素
日=lst[0]
月份=第一个月[1]
年份=lst[2]
acc.append(str(日)+'/'+str(月)+'/'+str(年))
返回组日期(lst[3:len(lst)],acc)
打印(groupToDate(lst1,[]))
打印(groupToDate(lst2,[]))
打印(groupToDate(lst3,[]))
打印(groupToDate(lst4,[]))
打印(groupToDate(lst5,[]))
打印(groupToDate(lst6,[]))

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

为什么每行末尾都有句点/句号?这将使您的程序无法运行。Python的行终止符是一个换行符,而不是
或其他任何内容。