简体   繁体   中英

Adding consecutive x values to a list

Suppose I have a list with items [123, 124, 125, ... 9820] and from that list I want to append to a second list with a string of every 8 items separated by a space up until the end. For example the list would have:

["123 124 125 126 127 128 129 130", "131, 132, 133, 134, 135, 136, 137, 138",..] etc.

What is the best way to do this in python? I have tried a naive solution of looping from 123 to 9820 but this takes way too much runtime and times out some of my simple tests I have set up. Are there any functions that would be useful to me?

Collect the elements into chunks of length 8 and use join() . Here's an example using an adapted recipe from itertools :

from itertools import zip_longest

lst = [str(x) for x in range(123, 9821)]


def grouper(iterable, n, fillvalue=""):
    "Collect data into fixed-length chunks or blocks"      
    args = [iter(iterable)] * n 
    return zip_longest(*args, fillvalue=fillvalue)

lst2 = [" ".join(x) for x in grouper(lst, 8)]

We have to jump by 8 index to get next item from items list.

Demo

  1. Consider items list from 1 to 999 numbers, Length of items list is 999 .
  2. Then use for loop with range function to jump by 8 index in a items list.
  3. Use append method of string to get final result.

code:

>>> items = range(1, 1000)
>>> len(items)
999
>>> output_str = ""
>>> for i in range(0, 999, 8):
...    output_str += " " + str(items[i])
... 
>>> output_str.strip()
'1 9 17 25 33 41 49 57 65 73 81 89 97 105 113 121 129 137 145 153 161 169 177 185 193 201 209 217 225 233 241 249 257 265 273 281 289 297 305 313 321 329 337 345 353 361 369 377 385 393 401 409 417 425 433 441 449 457 465 473 481 489 497 505 513 521 529 537 545 553 561 569 577 585 593 601 609 617 625 633 641 649 657 665 673 681 689 697 705 713 721 729 737 745 753 761 769 777 785 793 801 809 817 825 833 841 849 857 865 873 881 889 897 905 913 921 929 937 945 953 961 969 977 985 993'
>>> 

I think this does the work you want:

The code:

list = [str(x) for x in range(123, 9821)]
results = []

for index in range(0, len(list), 8):
  results.append(" ".join(list[index:index+8]))

print(results)

The output:

[
    '123 124 125 126 127 128 129 130', 
    '131 132 133 134 135 136 137 138', 
    '139 140 141 142 143 144 145 146', 
    '147 148 149 150 151 152 153 154', 
    '155 156 157 158 159 160 161 162',
    ...
    '9795 9796 9797 9798 9799 9800 9801 9802', 
    '9803 9804 9805 9806 9807 9808 9809 9810', 
    '9811 9812 9813 9814 9815 9816 9817 9818', 
    '9819 9820'
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM