【问题标题】:Array Grouping and Identify in pythonpython中的数组分组和识别
【发布时间】:2015-02-25 01:03:22
【问题描述】:

我正在尝试对数组“frog”中的某些数据进行分组。数组“青蛙”看起来像:

285,1944,10,12,579
286,1944,11,13,540
287,1944,12,14,550
285,1945,10,12,536
286,1945,11,13,504
287,1945,12,14,508
285,1946,10,12,522
286,1946,11,13,490
287,1946,12,14,486

顺序是“一年中的日子”、年、月、“月中的日子”和钱。我想将所有“一年中的一天”与正确的月份和“一个月中的一天”放在一起。所以有三个约束(一年中的一天,一个月,一个月的一天)。一个示例输出数组将类似于:

285,1944,10,12,579 
285,1945,10,12,536
285,1946,10,12,522

我不确定该怎么做。在这种情况下,是否有比使用 while 循环或 for 循环更快的方法?如果您希望我解释更多,请告诉我。

谢谢

【问题讨论】:

  • 你的青蛙数组是 1 还是 2d,你的输出只是基于“一年中的一天”和“一个月的一天”索引的有序分组吗?

标签: python arrays


【解决方案1】:

Python 有一个 sort 函数,它带有一个 key 函数,可以任意定义。在这种情况下,我们可以定义一个简单的函数,甚至是一个lambda 来做我们想做的事情。

但是,正如@Vasif 所提到的,闰年会有问题,因为例如,第 285 天可能是一年的 10 月 13 日,但随后是闰年的 10 月 12 日,因此要求三元组作为约束...

无论如何:

# let's assume you've read in your file with something like csvreader
# so you've got a list of lists, similar to what @Vasif shows
sorted_a = sorted(a, key=lambda row: (row[0], row[2], row[3]))

这将创建一个新数组,其中所有内容首先按“Day of Year”排序(因此所有 285 将在一起),然后按“Month”,然后按“Day”。

为了完整起见,我们可以就地操作数组:

a.sort(key=lambda row:(row[0], row[2], row[3]))

对于更复杂的事情(这里没有必要,但可能很高兴看到):

def keyfunc(row):
    # could do anything you want with more complex data:
    # maybe row[0] is an index into a database that you query, or 
    # a URL that you request the page of, parse, and process somehow, etc...
    return (row[0], row[2], row[3])

sorted_a = sorted(a, key=keyfunc)
## or again:
a.sort(key=keyfunc)

【讨论】:

    【解决方案2】:

    我在下面给你一个解决方案。 我如何不确定你的输出。 1944年是闰年。

    import datetime as dt
    
    a = [[285,1944,10,12,579],
    [286,1944,11,13,540],
    [287,1944,12,14,550],
    [285,1945,10,12,536],
    [286,1945,11,13,504],
    [287,1945,12,14,508],
    [285,1946,10,12,522],
    [286,1946,11,13,490],
    [287,1946,12,14,486]]
    
    def solution(frog):
    	goodlist=[]
    	for l in frog:
    		if isGood(l):
    			print l 
    			goodlist.append(l)
    		print l , 'rejected'
    	return goodlist
    
    
    def isGood(l):
    	[days,year,month,day,money] = l
    
    
    
    	# http://stackoverflow.com/questions/2427555/python-question-year-and-day-of-year-to-date
    	date = dt.datetime(year, 1, 1) + dt.timedelta(days - 1)
    	# print date.month, date.day
    	if date.month == month and date.day == day :
    		return True
    	return False
    
    # print isGood([285,1944,10,12,579])
    print solution(a)

    【讨论】:

    • 我通过删除数据集中的所有 2-29 来计算闰年。我的数据集是一个大型二维数组。这有索引(一年中的一天)、年、月、日和货币作为标题。我需要对排序后的数据做的是取多年来每天货币输出的平均值。因此,在我 100 多年的数据中,所有 10 月 5 日的货币产出都需要取平均值。最后,我正在寻找 100 年来每天的 365 次货币输出平均值。对不起,如果我让事情变得更加混乱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2023-02-09
    • 1970-01-01
    • 2017-07-13
    • 2013-11-04
    相关资源
    最近更新 更多