简体   繁体   中英

Python: loop through list item x times?

I am using Python2.7 and I would like to loop through a list x times.

a=['string1','string2','string3','string4','string5']
for item in a:
  print item

The above code will print all five items in the list, What if I just want to print the first 3 items? I searched over the internet but couldn't find an answer, it seems that xrange() will do the trick, but I can't figure out how.

Thanks for your help!

Sequence Slicing is what you are looking for. In this case, you need to slice the sequence to the first three elements to get them printed.

a=['string1','string2','string3','string4','string5']
for item in a[:3]:
      print item

Even, you don't need to loop over the sequence, just join it with a newline and print it

print '\n'.join(a[:3])

I think this would be considered pythonic :

for item in a[:3]:
    print item

Edit : since a matter of seconds made this answer redundant, I will try to provide some background information:

Array slicing allows for quick selection in sequences like Lists of Strings. A subsequence of a one-dimensional sequence can be specified by the indices of left and right endpoints:

>>> [1,2,3,4,5][:3] # every item with an index position < 3
[1, 2, 3]
>>> [1,2,3,4,5][3:] # every item with an index position >= 3
[4, 5]
>>> [1,2,3,4,5][2:3] # every item with an index position within the interval [2,3)
[3]

Note that the left endpoint is included , the right one is not. You can add a third argument to select only every n th element of a sequence:

>>> [1,2,3,4,5][::2] # select every second item from list
[1, 3, 5]
>>> [1,2,3,4,5][::-1] # select every single item in reverse order
[5,4,3,2,1]
>>> [1,2,3,4,5][1:4:2] # every second item from subsequence [1,4) = [2,3,4]
[2, 4]

By converting lists to numpy arrays, it is even possible to perform multi-dimensional slicing:

>>> numpy.array([[1,2,3,4,5], [1,2,3,4,5]])[:, ::2]
array([[1, 3, 5],
       [1, 3, 5]])
a=['string1','string2','string3','string4','string5']
for i in xrange(3):
    print a[i]

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