简体   繁体   English

如何将此 Python 变量分配给我正在循环的列表?

[英]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.感谢所有让我的第一篇 StackOverflow 帖子变得非常有用和有趣的人。

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.说明:您的任务是将变量 names_and_ranks 分配给一个列表,其中每个元素都等于城市名称及其对应的排名。 For example, the first element would be, "1. Buenos Aires" and the second would be "2. Toronto".例如,第一个元素是“1. Buenos Aires”,第二个元素是“2. Toronto”。 Use a for loop and the lists city_indices and city_names to accomplish this.使用 for 循环和列表city_indicescity_names来完成此操作。 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.查看 f-string 插值以了解我们如何将值传递到字符串中。 Remember that list indices start at zero, but we want our names_and_ranks list to start at one!请记住,列表索引从 0 开始,但我们希望我们的names_and_ranks列表从 1 开始!

Here is what I have:这是我所拥有的:

The code city_indices only gives me "11" so I have made it into a list代码city_indices只给我“11”所以我把它做成了一个列表

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生成的列表应该分配给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.但是,它似乎没有正确对应 names_and_ranks 变量。 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.我得到了列表中的最后一项 (#12).... 请记住,列表索引是 0 - 11,但我将输出编号为 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.一旦我分配了这个变量并运行一个成功的循环来显示一个从 1 开始的城市列表。我需要在新列表中打印不同的元素。

ie names_and_ranks[0] should return "1. Buenos Aires"names_and_ranks[0]应返回“1.布宜诺斯艾利斯”

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这将返回 0 foo 1 bar 2 baz

here is using f'strings, this returns same as above:这里使用 f'strings,返回与上面相同:

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.输出:['1。 Buenos Aires', '2.布宜诺斯艾利斯','2。 Toronto', '3.多伦多','3。 Marakesh', '4.马拉喀什','4。 Albuquerque', '5.阿尔伯克基','5。 Los Cabos', '6.洛斯卡沃斯','6。 Greenville', '7.格林维尔','7。 Archipelago Sea', '8.群岛海','8。 Pyeongchang', '9.平昌', '9. Walla Walla Valley', '10.瓦拉瓦拉谷','10。 Salina Island', '11.萨利纳岛','11。 Solta', '12.索尔塔','12。 Iguazu Falls']伊瓜苏瀑布']

EDIT: as the questioner wants names_and_ranks[8] returning '8.编辑:因为提问者希望 names_and_ranks[8] 返回 '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.哪个(我猜是一个索引)应该从 0 开始而不是从 -1 开始。

Reason,原因,

in Python, -1 points to last element of list/string/.. and -2 as second last element and so on.在 Python 中,-1 指向 list/string/.. 的最后一个元素,-2 作为倒数第二个元素,依此类推。 so, I recommend you should change only: city_indices = 0所以,我建议你应该只改变: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...我希望这可以帮助其他人在 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python中通过变量分配ROWID? - How can I assign the ROWID through a variable in Python? Python:如何将函数分配给变量? - Python: how can I assign a function to a variable? 如何创建 SQL 表键,其中包含循环通过 Python 中的列表的项目 - How can I create SQL table keys with items from looping through a list in Python 在 python 中循环遍历列表的一部分时,我无法正确索引 - when looping through a slice of a list in python, I am not able to index correctly Python:如何在遍历列表时为不同的消息分配名称? - Python: How can I assign names different messages while iterating through a list? 我可以在循环时分配和访问 Tkinter 列表框中的变量吗? - Can I assign and access variable inside Tkinter Listbox while for looping? 我正在尝试在python 2.7中读取几个csv文件并分配给列表变量 - I am trying to read several csv files in python 2.7 and assign to a list variable 如何对输入列表进行排名并为其分配变量以返回给用户? - How can I rank a input list and assign it a variable to return to user? 如何从列表中删除项目,并将其分配给变量? - How can I remove an item from a list, and assign it to a variable? 如何将列表中的项目用作变量并为其赋值? - How can I use items from list as variable and assign values to it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM