按照特定模式创建列表的简便方法是什么,例如从x开始,添加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 :(得分:1)
Python在itertools中提供了一个cycle
函数,对此有用:
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)
版本3.2中添加了
答案 1 :(得分: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
编辑: 您也可以使用随机函数
import random
result_list = AddList(random.sample(range(-100, 100), 10))
print result_list