首页 > 解决方案 > 调用后创建带有索引的函数

问题描述

我目前被我需要制作的这个功能所困扰。我只是想知道是否有人可以帮助我在每次调用函数时为 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')

标签: pythonpython-3.x

解决方案


您的意思是为每个新循环设置一个索引,或者为您获得的每种战利品盒设置一个索引?

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

推荐阅读