python - 调用后创建带有索引的函数
问题描述
我目前被我需要制作的这个功能所困扰。我只是想知道是否有人可以帮助我在每次调用函数时为 4 行添加索引。这是我现在所处的位置,但我没有得到正确的索引。任何提示将不胜感激。谢谢
import random
def open_box(num_items):
num_items = 4
print('Opening loot box:')
for item in range(4):
items = item + 1
item = random.randint(0, 100)
if item <= 5:
print(' Item 1 of 4... Legendary Item')
elif item <= 15:
print(' Item 2 of 4... Epic Item')
elif item <= 35:
print(' Item 3 of 4... Rare Item')
elif item <= 100:
print(' Item 4 of 4... Common Item')
解决方案
您的意思是为每个新循环设置一个索引,或者为您获得的每种战利品盒设置一个索引?
print('Opening loot box:')
import random
for i, item in enumerate(range(4)):
items = item + 1
item = random.randint(0, 100)
print(f'{i}:', end='')
if item <= 5:
print(' Item 1 of 4... Legendary Item')
elif item <= 15:
print(' Item 2 of 4... Epic Item')
elif item <= 35:
print(' Item 3 of 4... Rare Item')
elif item <= 100:
print(' Item 4 of 4... Common Item')
>>>
Opening loot box:
0: Item 4 of 4... Common Item
1: Item 2 of 4... Epic Item
2: Item 4 of 4... Common Item
3: Item 4 of 4... Common Item
推荐阅读
- amazon-web-services - Amazon S3 Glacier 与 Glacier 存储类
- angular - 在设计使用组合优于继承的 Angular 组件时如何处理依赖注入?
- javascript - Lyniate Rhapsody:在对象中找不到函数 toISOString
- powerbi - 是否可以将表格的每一列值除以powerbi中另一个表格的每一列值?
- c# - 验证方法未在按钮单击 C# 时调用
- rpm - RPM 包不会安装依赖项
- r - 定义子字符串是匹配原始字符串的左侧还是右侧
- python - 如何在此列表列表中将字符串转换为十进制?
- python - 在 withcolumn Pyspark 之后包含过滤器
- javascript - 作为维护者和发布者,如何声明 npm 包中的安全漏洞?