练习python:如何将列表中的元素分组?
问题描述:
我试图解决下面的练习,而不使用日期时间!练习python:如何将列表中的元素分组?
练习:
定int值的列表,这样,前三INT代表日期, 第二个三个ELEMENTI代表通过分组 每三联一体字符串的日期etc..modify 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, []))
这也是解决这样的问题,如果你不想使用列表理解或在每行的末尾GROUPBY
为什么你有时间/句号的基本方法?这会让你的程序不能运行。 Python的行结束符是一个换行符,不是'''或';'或其他任何东西。 – MattDMo