简体   繁体   中英

How do I get certain values from a list in a for loop in Python?

If I have a list:

myList = ['car a', 5000, 'great value', 'car b', 8000, 'good value']

How can I do this in a for loop : (print(myList[0]) print(myList[3]))

adding 3 till the end of the list.

I tried:

for carName in myList:
    carName = myList[0 + 3]> # I am stuck here
    print carName

Thanks for the help!

You can slice your list using [start:end:step] notation, only supplying the step component:

myList = ['car a', 5000, 'great value', 'car b', 8000, 'good value']

for item in myList[::3]:
    print(item)

# car a
# car b

To avoid the expense of building a list for this purpose, you can use itertools.islice :

from itertools import islice

for item in islice(myList, 0, None, 3):
    print(item)

This is how you could use a for loop to achieve that:

myList = ['car a', 5000, 'great value', 'car b', 8000, 'good value']

for carName in range(0, len(myList), 3):
    print(myList[carName])

put the step size - 3

Syntax of For loop -

for i in range (start,stop,step):

Ex- Code to print even numbers

for i in range(0,11,2):
    print(i)

output-2,4,6,8,10

I think what you are looking for is modulo % 3 == 0

myList = ['car a', 5000, 'great value', 'car b', 8000, 'good value']

This will print the first element and any multiple of three no matter how big the list is.

for i, x in enumerate(myList):
    if i % 3 == 0:
        print(myList[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