تخفيض عدد الإدخالات في القائمة (بدون استيفاء)
-
26-09-2019 - |
سؤال
لدي قائمة بيثون مع عدد من الإدخالات ، والتي أحتاج إلى إسقاطها باستخدام أي منهما:
- الحد الأقصى لعدد الصفوف. على سبيل المثال ، الحد من قائمة 1234 إدخالات إلى 1000.
- نسبة من الصفوف الأصلية. على سبيل المثال ، جعل القائمة 1/3 طولها الأصلي.
(أحتاج إلى أن أكون قادرًا على القيام في كلا الاتجاهين ، ولكن يتم استخدام واحدة فقط في وقت واحد).
أعتقد أنه بالنسبة للحد الأقصى لعدد الصفوف ، يمكنني فقط حساب النسبة المطلوبة وتمرير ذلك إلى مُنساق النسب:
def downsample_to_max(self, rows, max_rows):
return downsample_to_proportion(rows, max_rows / float(len(rows)))
... لذلك أنا حقًا بحاجة فقط إلى وظيفة انخفاض. أي تلميحات من فضلك؟
تعديل: تحتوي القائمة على كائنات ، وليس قيمًا رقمية ، لذا لا أحتاج إلى الاستيفاء. إسقاط الأشياء بخير.
المحلول:
def downsample_to_proportion(self, rows, proportion):
counter = 0.0
last_counter = None
results = []
for row in rows:
counter += proportion
if int(counter) != last_counter:
results.append(row)
last_counter = int(counter)
return results
شكرًا.
المحلول
الحفاظ على عداد ، والتي تقوم بزيادة القيمة الثانية. أرضية في كل مرة ، وتسفر عن القيمة في هذا الفهرس.
نصائح أخرى
يمكنك استخدام islice
من عند itertools
:
from itertools import islice
def downsample_to_proportion(rows, proportion=1):
return list(islice(rows, 0, len(rows), int(1/proportion)))
الاستخدام:
x = range(1,10)
print downsample_to_proportion(x, 0.3)
# [1, 4, 7]
بدلاً من islice()
+ list()
من الأكثر فاعلية استخدام بناء جملة Slice مباشرة إذا كان الإدخال بالفعل نوع تسلسل:
def downsample_to_proportion(rows, proportion):
return rows[::int(1 / proportion)]
قد يكون هذا الحل مبالاة بعض الشيء للملصق الأصلي ، لكنني اعتقدت أنني سأشارك الرمز الذي كنت أستخدمه لحل هذا ومشاكل مماثلة.
إنه طويل بعض الشيء (حوالي 90 سطرًا) ، ولكن إذا كان لديك هذه الحاجة في كثير من الأحيان ، فأريد أن يكون ذلك سهلاً للاستخدام ، ويحتاج إلى بيئة خالية من التبعية النقية ، فإنني أعتقد أنها قد تكون مفيدة.
في الأساس ، الشيء الوحيد الذي عليك القيام به هو تمرير قائمتك إلى الوظيفة وأخبرها بالطول الذي تريد أن تكون قائمتك الجديدة ، وستقوم الوظيفة أيضًا:
- تقليص الحجم قائمتك عن طريق إسقاط العناصر إذا كان الطول الجديد أصغر ، مثل الإجابات السابقة المقترحة بالفعل.
- تمتد/راقية قائمتك (عكس تقليص حجمها) إذا كان الطول الجديد أكبر ، مع الخيار المضافة الذي يمكنك تحديد ما إذا كنت كذلك:
- تداخل خطيا BW القيم المعروفة (يتم اختيارها تلقائيًا إذا كانت القائمة تحتوي على ints أو عوامات)
- تكرار كل قيمة بحيث يشغلون حجمًا نسبيًا للقائمة الجديدة (تم اختيارها تلقائيًا إذا كانت القائمة تحتوي على غير الأرقام)
- قم بفصل القيم الأصلية واترك الثغرات بينهما
يتم جمع كل شيء داخل وظيفة واحدة ، لذا إذا كنت في حاجة إليها ، فما عليك سوى نسخها ولصقها في البرنامج النصي ويمكنك البدء في استخدامها على الفور.
على سبيل المثال قد تقول:
origlist = [0,None,None,30,None,50,60,70,None,None,100]
resizedlist = ResizeList(testlist, 21)
print(resizedlist)
واحصل على
[0, 5.00000000001, 9.9999999999900009, 15.0, 20.000000000010001, 24.999999999989999, 30, 35.0, 40.0, 45.0, 50.0, 55.0, 60.0, 65.0, 70, 75.000000000010004, 79.999999999989996, 85.0, 90.000000000010004, 94.999999999989996, 100]
لاحظ أن عدم الدقة البسيطة ستحدث بسبب قيود النقاط العائمة. أيضًا ، كتبت هذا لـ Python 2.x ، حتى لا تستخدمه على Python 3.x فقط أضف سطرًا واحدًا يقول xrange = range
.
وهنا خدعة أنيقة للالتحاق بين المكونات الفرعية في قائمة القوائم. لذلك على سبيل المثال ، يمكنك بسهولة الاستيفاء بين tuples Color RGB لإنشاء تدرج لون من X NR من الخطوات. بافتراض قائمة من tuples Color RGB من 3 ومتغير الطول المتدرج المطلوب ، يمكنك القيام بذلك مع:
crosssections = zip(*rgbtuples)
grad_crosssections = ( ResizeList(spectrum,GRADIENTLENGTH) for spectrum in crosssections )
rgb_gradient = [list(each) for each in zip(*grad_crosssections)]
ربما قد تحتاج إلى عدد قليل من التحسينات ، كان عليّ أن أفعل الكثير من التجارب. إذا شعرت أنه يمكنك تحسينها ، فلا تتردد في تحرير رسالتي. هنا هو الرمز:
def ResizeList(rows, newlength, stretchmethod="not specified", gapvalue=None):
"""
Resizes (up or down) and returns a new list of a given size, based on an input list.
- rows: the input list, which can contain any type of value or item (except if using the interpolate stretchmethod which requires floats or ints only)
- newlength: the new length of the output list (if this is the same as the input list then the original list will be returned immediately)
- stretchmethod: if the list is being stretched, this decides how to do it. Valid values are:
- 'interpolate'
- linearly interpolate between the known values (automatically chosen if list contains ints or floats)
- 'duplicate'
- duplicate each value so they occupy a proportional size of the new list (automatically chosen if the list contains non-numbers)
- 'spread'
- drags the original values apart and leaves gaps as defined by the gapvalue option
- gapvalue: a value that will be used as gaps to fill in between the original values when using the 'spread' stretchmethod
"""
#return input as is if no difference in length
if newlength == len(rows):
return rows
#set auto stretchmode
if stretchmethod == "not specified":
if isinstance(rows[0], (int,float)):
stretchmethod = "interpolate"
else:
stretchmethod = "duplicate"
#reduce newlength
newlength -= 1
#assign first value
outlist = [rows[0]]
writinggapsflag = False
if rows[1] == gapvalue:
writinggapsflag = True
relspreadindexgen = (index/float(len(rows)-1) for index in xrange(1,len(rows))) #warning a little hacky by skipping first index cus is assigned auto
relspreadindex = next(relspreadindexgen)
spreadflag = False
gapcount = 0
for outlistindex in xrange(1, newlength):
#relative positions
rel = outlistindex/float(newlength)
relindex = (len(rows)-1) * rel
basenr,decimals = str(relindex).split(".")
relbwindex = float("0."+decimals)
#determine equivalent value
if stretchmethod=="interpolate":
#test for gap
maybecurrelval = rows[int(relindex)]
maybenextrelval = rows[int(relindex)+1]
if maybecurrelval == gapvalue:
#found gapvalue, so skipping and waiting for valid value to interpolate and add to outlist
gapcount += 1
continue
#test whether to interpolate for previous gaps
if gapcount > 0:
#found a valid value after skipping gapvalues so this is where it interpolates all of them from last valid value to this one
startvalue = outlist[-1]
endindex = int(relindex)
endvalue = rows[endindex]
gapstointerpolate = gapcount
allinterpolatedgaps = Resize([startvalue,endvalue],gapstointerpolate+3)
outlist.extend(allinterpolatedgaps[1:-1])
gapcount = 0
writinggapsflag = False
#interpolate value
currelval = rows[int(relindex)]
lookahead = 1
nextrelval = rows[int(relindex)+lookahead]
if nextrelval == gapvalue:
if writinggapsflag:
continue
relbwval = currelval
writinggapsflag = True
else:
relbwval = currelval + (nextrelval - currelval) * relbwindex #basenr pluss interindex percent interpolation of diff to next item
elif stretchmethod=="duplicate":
relbwval = rows[int(round(relindex))] #no interpolation possible, so just copy each time
elif stretchmethod=="spread":
if rel >= relspreadindex:
spreadindex = int(len(rows)*relspreadindex)
relbwval = rows[spreadindex] #spread values further apart so as to leave gaps in between
relspreadindex = next(relspreadindexgen)
else:
relbwval = gapvalue
#assign each value
outlist.append(relbwval)
#assign last value
if gapcount > 0:
#this last value also has to interpolate for previous gaps
startvalue = outlist[-1]
endvalue = rows[-1]
gapstointerpolate = gapcount
allinterpolatedgaps = Resize([startvalue,endvalue],gapstointerpolate+3)
outlist.extend(allinterpolatedgaps[1:-1])
outlist.append(rows[-1])
gapcount = 0
writinggapsflag = False
else:
outlist.append(rows[-1])
return outlist
لا يمكن عشوائي. choices () حل مشكلتك؟ المزيد من الأمثلة متوفرة هنا