简体   繁体   中英

Most pythonic way to get a range from the length of a list?

I'm trying to get some slices from some tuples, that look like this:

classes = ('1 hrs                   A', '2 hrs                   A', '3 hrs                   A', '3 hrs                   B', '3 hrs                   C', '3 hrs                   C', '3 hrs                   C')

What I have done is:

for i in range(len(classes)):
    print(classes[i][0])

Which produces the desired effect of only printing out the integer portion, but it's kind of ugly with the whole range(len(classes)) portion, I was wondering if there was a different way to acheive the same results?

You could just do:

for i in classes:
    print(i[0])

The cleanest way is probably to iterate over classes itself, and - since you're only interested in the first element - unpack them:

for item, *_ in classes:
    print(item)

Note, however, that this only works when the number is a single character. If it has multiple characters, you should split the string:

for item in classes:
    print(item.split()[0])

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