Python - creating patterned lists
-
13-07-2021 - |
質問
In my current Python project, I need to create some long lists of integers for later use in plots. Currently I'm attacking this in the following way:
volume_axis = []
for values in stripped_header:
for doses in range(100):
volume_axis.append(int(values))
This code will append to my blank list, giving me the first value in stripped header 100 times, then the next value in stripped header 100 times etc.
Is there a more elegant and pythonesque way to accomplish this?
解決
for values in stripped_header:
volume_axis += [int(values)] * 100
or using itertools (may be more efficient)
from itertools import repeat
for values in stripped_header:
volume_axis += repeat(int(values), 100)
他のヒント
There have been a number of good pythonic answers to this question, but if your happy to use numpy (which is a dependency of matplotlib anyway) then this is a one liner:
>>> import numpy
>>> stripped_header = [1, 2, 4]
>>>
>>> numpy.repeat(stripped_header, 3)
array([1, 1, 1, 2, 2, 2, 4, 4, 4])
HTH
Using itertools
:
from itertools import chain, repeat
list(chain.from_iterable(repeat(int(n), 100) for n in sh))
consider sh
represent stripped_header
In [1]: sh = [1,2,3,4]
In [2]: [x for x in sh for y in [sh]*5]
Out[2]: [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]
or you can also go with for ease of understanding
In [3]: [x for x in sh for y in range(5)]
Out[3]: [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4]
所属していません StackOverflow