简体   繁体   中英

Enumerate clarification

This is the code that I was given:

cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"]
heights = [72, 68, 72, 66, 76]

print(cast)

This is the desired output:

['Barney Stinson 72', 'Robin Scherbatsky 68', 'Ted Mosby 72', 'Lily Aldrin 66', 'Marshall Eriksen 76']

This is the solution:

cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"]
heights = [72, 68, 72, 66, 76]

for i, character in enumerate(cast):
    cast[i] = character + " " + str(heights[i])

print(cast)

This is the question for this piece of code:

for i, character in enumerate(cast):
    cast[i] = character + " " + str(heights[i])

Why are the putting cast[i] and heights[i] and not only cast/heights? If it is a enumerate function is it supposed to number all names?

example:

letters = ['a', 'b', 'c', 'd', 'e']
for i, letter in enumerate(letters):
    print(i, letter)

This code would output:

0 a
1 b
2 c
3 d
4 e

You're modifying the characters of cast while you're iterating over it while also taking the position of the same character in the heights list.

You cannot use height because that's not a valid variable name in that loop and heights is the entire list; go ahead and try using it, it won't give you the desired output

If you did the following, then the cast list wouldn't change after the loop

character += " " + str(heights[i])

Note: zip(cast, height) will give you very similar output

For example,

print([c + " " + h in zip(cast, heights)]) 

Regarding your question:

Why are the putting cast[i] and heights[i] and not only cast/heights? If it is a enumerate function is it supposed to number all names?

When you create a for loop using enumerate() , like this:

for counter, value in enumerate(some_list):

The first variable counter is equal to the index of the list, while value is equal to the element present in the list at that index.

Source

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