简体   繁体   中英

PYTHON: Print X items of a list

I have this code:

U = [1,2,3,4,5,6,7,8,9,10,11,12]

def bla(anzahl):
    zaehlwerk = 0
    while zaehlwerk < anzahl:
        for x in U:
            zaehlwerk = zaehlwerk +1
            print x

my query:

bla(3)

I hoped that now I would get the first 3 list items, but instead I get the whole list.

1
2
3
4
5
6
7
8
9
10
11
12

I tried to debug because I thought that maybe the counter wouldn't work, but it does. But then where is my error?

use slicing :

>>> U = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> U[:3]
[1, 2, 3]

U[stat-index:end-index] , you will get element from start-index to one less end-index, as in above example

>>>U[2:6]
[3, 4, 5, 6]

what you need to do is this using slicing:

def print_list(n):
    print "\n".join(map(str,U[:n]))
print_list(3)

output:

1
2
3
for x in U:

is the innermost loop. That is making sure you iterate over everything.

As is you can modify your code to look like

def bla(anzahl):
    zaehlwerk = 0
    while zaehlwerk < anzahl:
        x = U[zaehlwerk]
        zaehlwerk = zaehlwerk +1
        print x

And that will work for what you want. But more concise would be to to use something like

for index in range(len(anzahl)):
    print U[index]

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