Python 切片 - 跳过一定数量的行[重复]

问题描述 投票:0回答:4

我目前有 500 行数据。我想使用前 50 行,然后跳过 50 行,依此类推。我该如何继续这样做?

python slice
4个回答
3
投票

这是更直观的解决方案

Numpy
。通过布尔数组过滤数据:

import numpy as np

x = np.array(range(0,500))
b = np.array(([True] * 50 + [False] * 50) * 5)
x[b]

2
投票

切片符号为

list[start:end]
,在您的情况下,您可以使用
xrange
,步长为
100
(
50*2
),然后只取前 50 行来完成您的任务:

rows = [x for x in xrange(0, 500)]

for x in xrange(0, len(rows), 100):
    print repr(rows[x:x+50]) # Do stuff here (iterate again if necessary)

[0, 1, 2, 3, ... 48, 49]
[100, 101, 102, 103, ... 148, 149] ...

1
投票
print([x for i, x in enumerate(range(500)) if divmod(i, 50)[0] % 2 == 0])

-1
投票

例如:

import numpy as np
x = np.array(range(0,500)) // assign numpy array of 500
b = np.array(([True] * 50 + [False] * 50) * 5)
print(x[b])

输出:

[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49 100 101 102 103
 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
 122 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 200 201 202 203 204 205 206 207
 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
 244 245 246 247 248 249 300 301 302 303 304 305 306 307 308 309 310 311
 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
 348 349 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449]
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.