限制python 2.7中列表中的元素

时间:2015-08-30 00:14:24

标签: python python-2.7

我有300多个元素的python列表。我试图将列表中的元素限制为一次只显示10个。

我这样想,这是一个列表中只有5个元素的例子:

items = ["one", "two", "three", "four", "five"]

max_num = 2

for item in items:
 # here I am not sure how I restrict the number elements from items

 # I hoping someone can walk me though the process on how to
 # achieve this.

4 个答案:

答案 0 :(得分:1)

有多种方法可以做到。

1。 (Pythonic方式)

@ aa333建议:

for item in items[:max_num]:
   print(item)

2。可能快一点:

for i in xrange(max_num):
   print(items[i])

3。使用while循环:

counter = 0
while counter < max_num:
   print(items[i])
   counter += 1

答案 1 :(得分:1)

试试这个。

a = range(300)
for i in range(len(a)):
    limit = 10;
    i=(i*limit)
    print a[i:(i+limit)]
    if(i>(len(a)-limit-1)):
        break;

这是基本答案。我相信有更好的逻辑可用。

Output is like:
[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]......

希望这是所需的输出。

答案 2 :(得分:1)

如果我正确理解了这个问题,可以通过以下方式完成:

from math import floor
from numpy import arange
max_num=10.
lis=arange(0,404)
len_num=int(floor(float(len(lis))/max_num))
for i in range(len_num):
  print lis[i*int(max_num):(i+1)*int(max_num)]
  wait=input()
print(lis[(i+1)*int(max_num):])

这样,您的列表会逐片显示,直到用户按下一个键才会显示下一个切片

答案 3 :(得分:1)

简单方法:

>>> m = 300
>>> k=range(m)
>>> s = 0
>>> e = 10
>>> while m > 0:
...  print k[s:e]
...  s+=10
...  e+=10
...  m-=10
...
[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]
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69]
[70, 71, 72, 73, 74, 75, 76, 77, 78, 79]
[80, 81, 82, 83, 84, 85, 86, 87, 88, 89]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
[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]
[150, 151, 152, 153, 154, 155, 156, 157, 158, 159]
[160, 161, 162, 163, 164, 165, 166, 167, 168, 169]
[170, 171, 172, 173, 174, 175, 176, 177, 178, 179]
[180, 181, 182, 183, 184, 185, 186, 187, 188, 189]
[190, 191, 192, 193, 194, 195, 196, 197, 198, 199]
[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]
[250, 251, 252, 253, 254, 255, 256, 257, 258, 259]
[260, 261, 262, 263, 264, 265, 266, 267, 268, 269]
[270, 271, 272, 273, 274, 275, 276, 277, 278, 279]
[280, 281, 282, 283, 284, 285, 286, 287, 288, 289]
[290, 291, 292, 293, 294, 295, 296, 297, 298, 299]