Группировка ближайших элементов из списка по разнице

Ваш код создаст запрос с переменными привязки. Вы можете проверить это, когда вы устанавливаете Hibernate logger org.hibernate.SQL для отладки в application.properties

logging.level.org.hibernate.SQL=DEBUG

Вы должны видеть заявление с? заполнители.

Использование переменных привязки предотвращает внедрение SQL. Подробнее об этой теме и о том, как вы ее протестировали:

https://vladmihalcea.com/a-beginners-guide-to-sql-injection-and-how-you-should- не допустить, что /

1
задан sharathchandramandadi 19 January 2019 в 18:11
поделиться

2 ответа

Еще одно решение с использованием простого цикла for:

tst = [1,3,4,6,8,22,24,25,26,67,68,70,72]    # considering this as already sorted. else use tst.sort()

il = []
ol = []
for k, v in enumerate(tst):                  # enumerate is used give index to list element
    if k > 0:                                # to avoid tst[-1] which will get the last element of the list
        if abs(tst[k] - tst[k-1]) < 3:       # check if differnce is less than 3
            if tst[k-1] not in il:           # insert to inner list "il" only if it doesn't already exist
                il.append(tst[k-1])
            if tst[k] not in il:             # insert to inner list "il" only if it doesn't already exist
                il.append(tst[k])
        else:
            ol.append(list(il))              # if difference is greater than 2 then append it to outer list "ol"
            il = []                          # clear the inner list "il"
ol.append(list(il))                          # finaly append the last "il" to "ol" which didnt went in else for our case "[67, 68, 70, 72]"
print (ol)

#Result: [[1, 3, 4, 6, 8], [22, 24, 25, 26], [67, 68, 70, 72]]
0
ответ дан Akash Swain 19 January 2019 в 18:11
поделиться

Мне нравится этот способ, определение метода среза и передача лямбда-предиката:

def slice_when(predicate, iterable):
  i, x, size = 0, 0, len(iterable)
  while i < size-1:
    if predicate(iterable[i], iterable[i+1]):
      yield iterable[x:i+1]
      x = i + 1
    i += 1
  yield iterable[x:size]

tst = [1,3,4,6,8,22,24,25,26,67,68,70,72]
slices = slice_when(lambda x,y: y - x > 2, tst)
print(list(slices))
#=> [[1, 3, 4, 6, 8], [22, 24, 25, 26], [67, 68, 70, 72]]

Полезно во многих случаях.

0
ответ дан iGian 19 January 2019 в 18:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: