简体   繁体   中英

How can I assign this Python variable to the list I am looping through?

Thank you to everyone who has made my first StackOverflow post extremely helpful and fun.

I have been working through this problem all day and have gotten to this point. I have it almost figured out.

Directions: Your task is to assign the variable names_and_ranks to a list, with each element equal to the city name and it's corresponding rank. For example, the first element would be, "1. Buenos Aires" and the second would be "2. Toronto". Use a for loop and the lists city_indices and city_names to accomplish this. We'll need to perform some nifty string interpolation to format our strings properly. Check out f-string interpolation to see how we can pass values into a string. Remember that list indices start at zero, but we want our names_and_ranks list to start at one!

Here is what I have:

The code city_indices only gives me "11" so I have made it into a list

city_indices = list(range(0, len(cities)))
city_indices

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
city_names

['Buenos Aires',
 'Toronto',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Pyeongchang',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls']

The original code that produced the correct list, but not assigned to the correct variable. The generated list should be assigned to names_and_ranks

city_indices = -1
names_and_ranks = [city_names[city_indices]]
for elements in city_names:
        city_indices += 1
        print(f'{city_indices+1}. {city_names[city_indices]}')
# write a for loop that adds the properly formatted string to the names_and_ranks list

Returns:

1. Buenos Aires
2. Toronto
3. Marakesh
4. Albuquerque
5. Los Cabos
6. Greenville
7. Archipelago Sea
8. Pyeongchang
9. Walla Walla Valley
10. Salina Island
11. Solta
12. Iguazu Falls

This list is correct with the correct numbering. However, it does not seem to correspond to the names_and_ranks variable correctly. In fact, when I run:

names_and_ranks[0]

I get the last item (#12) on my list.... Keep in mind that the list index is 0 - 11, but I am numbering the output 0 - 12.

Any ideas? Once I assign this variable and run a successful loop to show a list of cities starting at 1. I will need to print the different elements in the new list.

ie names_and_ranks[0] should return "1. Buenos Aires"

Current result from running:

names_and_ranks[0] # should return '1. Buenos Aires'



IndexErrorTraceback (most recent call last)
<ipython-input-152-871e7a906308> in <module>
----> 1 names_and_ranks[0] # '1. Buenos Aires'
      2  # '2. Toronto'
      3  # '12. Iguazu Falls'

IndexError: list index out of range

How about using enumerate? You can use index, easily for example,

for index, value in enumerate(['foo', 'bar', 'baz']):
    print(index, value)

this returns 0 foo 1 bar 2 baz

here is using f'strings, this returns same as above:

city_names = ['Buenos Aires',
 'Toronto',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Pyeongchang',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls']

names_and_ranks = []
for index,city in enumerate(city_names):
        names_and_ranks.append(f'{index+1}. {city}')
print(names_and_ranks)

output: ['1. Buenos Aires', '2. Toronto', '3. Marakesh', '4. Albuquerque', '5. Los Cabos', '6. Greenville', '7. Archipelago Sea', '8. Pyeongchang', '9. Walla Walla Valley', '10. Salina Island', '11. Solta', '12. Iguazu Falls']

EDIT: as the questioner wants names_and_ranks[8] returning '8. Pyeongchang' this is the edit:

city_names = ['Buenos Aires',
 'Toronto',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Pyeongchang',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls']

names_and_ranks = [0]
city_indices = 1
for city in city_names:
        names_and_ranks.insert(city_indices,f'{city_indices}. {city}')
        city_indices+=1

print(names_and_ranks[8])

Here's one way to do:

names_and_ranks = [f'{i}. {x}' for i,x in enumerate(l, 1)]

print(names_and_ranks[0])
1. Buenos Aires

your entire code is correct except for the first line:

city_indices = -1

which (is an index, i guess) should start from 0 and NOT from -1.

Reason,

in Python, -1 points to last element of list/string/.. and -2 as second last element and so on. so, I recommend you should change only: city_indices = 0

and then change the further code based on this line.

city_indices = 0
names_and_ranks = [city_names[city_indices]]
for elements in city_names:
    print(f'{city_indices+1}. {city_names[city_indices]}')
    city_indices += 1

I moved on after realizing I probably was spending way too much time on something relatively simple. I found the solutions manual. Here is the correct answer. I hope this might help someone else working on the Learn.co Flatiron School Data Science Pre-Work...

names_and_ranks = []
for elements in city_indices:
        names_and_ranks.append(f"{elements + 1}. {city_names[elements]}")

names_and_ranks

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