2016-03-04 3 views
0

Что представляет собой простой способ создать список, следующий за определенным шаблоном, например. начать с й, добавить 1, добавить 3, добавить 1, добавить 3, ...Создайте список, который следует за определенным шаблоном создания

я придумал этот метод, но есть, конечно, лучше (более компактный) способ:

i = 0 
n = 100 
l = [] 
for x in range(int(n/2)): 
    i = i + 1 
    l.append(i) 
    i = i + 3 
    l.append(i) 

который создает список

[1, 4, 5, 8, 9, 12, 13, 16, 17, 20, 21, 24, 25, 28, 29, 32, 33, 36, 37, 40, 41, 44, 45, 48, 49, 52, 53, 56, 57, 60, 61, 64, 65, 68, 69, 72, 73, 76, 77, 80, 81, 84, 85, 88, 89, 92, 93, 96, 97, 100, 101, 104, 105, 108, 109, 112, 113, 116, 117, 120, 121, 124, 125, 128, 129, 132, 133, 136, 137, 140, 141, 144, 145, 148, 149, 152, 153, 156, 157, 160, 161, 164, 165, 168, 169, 172, 173, 176, 177, 180, 181, 184, 185, 188, 189, 192, 193, 196, 197, 200] 

насчет более сложных моделей, как +1, -2, +3, +1, -2, +3, ...

+0

Ваш код набрасывает 'TypeError' на данный момент. Каков желаемый результат в вашем примере? – gtlambert

+0

извините, там, где несколько (немых) синтаксических ошибок. Я исправил их сейчас! – reox

ответ

1

Python предоставляет cycle функцию в itertools, что полезен:

from itertools import cycle 

i = 0 
n = 10 
l = [] 
step = cycle([1, -2, 3]) 

for _ in range(n): 
    i += next(step) 
    l.append(i) 

print(l) 

Давать вам:

[1, -1, 2, 3, 1, 4, 5, 3, 6, 7] 

Или же вы можете сделать следующий один лайнер:

from itertools import accumulate, islice, cycle 
import operator 

l = list(accumulate(islice(cycle([1, -2, 3]), 10), operator.add)) 
print(l) 

accumulate был добавлен в версии 3.2

+0

Версия 'accumulate' хороша до тех пор, пока' i == 0' ... –

+0

@JonClements no вы можете использовать здесь здесь, чтобы дать ему произвольный стартовый номер: 'l = list (accumulate ([10] + list (islice (цикл ([1, -2, 3]), 9)), operator.add)) 'idk, может быть, не самый изящный способ, но он работает – reox

+0

@reox oh - он может обрабатываться различными способами - Я просто указывал, что решение накопления, как предлагалось, работает по совпадению, что 'i == 0' работает, но оно не идентично циклу for, использующему цикл, где' i! = 0' –

0
# Function 
# Can accept an existing list to be added to (_result_list) which is optional 
# If _result_list is not included it is created from scratch 

def AddList(_factors_list, _result_list = []): 
    # Loop through the _factors_list (values to be added) 
    for _value in _factors_list: 
     # If _result_list (either passed in or created by function) contains 
     # no values, add the first item from _factors_list as the first entry 
     if len(_result_list) < 1: 
      _result_list.append(_value) 
      continue # Go to the next item in the _factors_list loop 
     # If _result_list already has values 
     else: 
      # _result_list[len(_result_list) - 1] takes the last item in list 
      # Don't use 'pop' as that removes the item 
      # Append the next item as 'last item' + 'current_loop_value' 
      _result_list.append(_result_list[len(_result_list) - 1] + _value) 
      continue # Go to the next item in the _factors_list loop 
    #Def all done. Return the _result_list 
    return _result_list 

result_list = [] # Optional, but can be an existing list 
factors_list = [1,-2,3, 5, -4] # Items to be added 
# test without existing list 
result_list = AddList(factors_list) 
print result_list 

# test WITH existing list 
result_list = [9, 8, 3] # Optional, but can be an existing list 
factors_list = [1,-2,3, 5, -4] # Items to be added 
result_list = AddList(factors_list, result_list) 
print result_list 

EDIT: Вы n также использовать случайную функцию

import random 
result_list = AddList(random.sample(range(-100, 100), 10)) 
print result_list 
Смежные вопросы