首页 > 解决方案 > 为什么这段代码表现得好像陷入了无限循环?

问题描述

我正在尝试创建条目(1000),并且从名称开始。我想出了一些名称,并计划复制添加了数字 0-9 的条目以创建更多唯一名称。所以我在 for 循环中使用了 for 循环。是否无法将索引更改为字符串并将其添加到列表中项目的末尾。

我考虑过递增,因为我最近在 C++ 中编写了很多代码,但这不起作用,因为当你使用 python 的 range 函数时不需要递增。我想过改变循环的顺序

name = ['event', 'thing going on', 'happening', 'what everyones talkin', 'that thing', 'the game', 'the play', 'outside time', 'social time', 'going out', 'having fun']
for index in range(10): 
    for item in name:
        name.append(item+str(index))
return name

我想打印出来['event0', 'thing going on1', ... 'having fun10']

谢谢!

标签: pythonlistnested-loops

解决方案


使用列表理解

  • enumerate() - 方法向可迭代对象添加一个计数器并以枚举对象的形式返回它。

前任。

name = ['event', 'thing going on', 'happening', 'what everyones talkin', 'that thing', 'the game', 'the play', 'outside time', 'social time', 'going out', 'having fun']
new_list = [x+str(index) for index,x in enumerate(name)]
print(new_list)

输出/输出:

['event0', 'thing going on1', 'happening2', 'what everyones talkin3', 'that thing4', 'the game5', 'the play6', 'outside time7', 'social time8', 'going out9', 'having fun10']

推荐阅读