python - 为什么这段代码表现得好像陷入了无限循环?
问题描述
我正在尝试创建条目(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']
谢谢!
解决方案
使用列表理解
- 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']
推荐阅读
- html - 将鼠标悬停在侧面导航中的 mat-item 上时,工具提示未启动
- python-3.x - 在python中遵循http重定向后如何获取最终url?
- python - 如何用三次样条或 pchip 插值 semilogx 图
- spring-boot - Thymleaf 不渲染结果,而是打印 spring boot app 的控制器方法的返回值
- llvm - 如何获取 LLVM 中的原始源代码和行号?
- android - Android Deep Link 不适用于较低的 API 版本(Android 5.0.2、API 21),但适用于 API 级别 28(Android 9.0)
- python - 神经网络 Librosa 导入错误 Python Tensorflow
- azure-cosmosdb - 如何仅比较 cosmos db 中的日期部分
- javascript - 在 JS 蛇游戏中,不能在画布边框周围骑蛇
- node.js - 如何将 npm 包更新为最新提交?