[英]How do I print the position of each item in the list?
I would like for the positions I selected to be printed out.我希望打印出我选择的职位。 I made this (with the help from here) to help me.我做了这个(在这里的帮助下)来帮助我。 This code is for me to easily work out level rewards.这段代码是为了让我轻松计算出等级奖励。 People tell me what level they're at and I enter those levels one by one, I'll then add points to their accounts using the command (>add-money...).人们告诉我他们处于什么级别,我一一输入这些级别,然后我将使用命令(>add-money...)将积分添加到他们的帐户中。 When writing out the reward I'm giving I want to be able to easily write what levels the rewards are from (ie what position in the list)在写出我给予的奖励时,我希望能够轻松地写出奖励的级别(即列表中的 position)
How can I make it so that I can print each position in the list I used?我怎样才能做到这一点,以便我可以打印我使用的列表中的每个 position?
My list:我的列表:
rewards = [0, 150, 225, 330, 500, 1000, 1500, 2250, 3400, 5000, 10000, 13000, 17000, 22000, 29000, 60000]
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
def rewardz():
# Running totals.
lists = []
total = 0
user=input('User -> ')
while True:
# Get reward level from the user. If not a valid reward level, stop.
level = input('-> ')
try:
level_num = int(level)
except ValueError:
break
if level_num not in range(len(rewards)):
break
# Add the reward to the lists and the total.
reward = rewards[level_num]
lists.append(reward)
total += reward
# Final output.
print(lists)
print(total, total*1000)
print()
print(" + ".join(str(i) for i in lists))
print('>add-money bank',user, total*1000)
print("\n-----########------\n\n")
rewardz()
rewardz()
What (or similar to what) I want the result to be:我希望结果是什么(或类似于什么):
[2, 4, 7, 1, 4, etc]
If all the values in rewards
list are unique you can get position of item in the list as such: rewards.index(rewards[level_num])
and then just append it to lists
list.如果rewards
列表中的所有值都是唯一的,您可以获得列表中项目的 position,如下所示: rewards.index(rewards[level_num])
,然后只需将 append 放入lists
列表。
Since you are asking the user to input the level you already have the level saved in level_num
.由于您要求用户输入级别,因此您已经将级别保存在level_num
中。 If you want to return it you could do lists.append((reward, level_num))
or for a possibly cleaner solution use a dictionary.如果您想返回它,您可以执行lists.append((reward, level_num))
或对于可能更清洁的解决方案使用字典。
lists = {"rewards": [],
"level": []}
And then to append to it you can do:然后到 append 到它,你可以这样做:
lists["rewards"].append(reward)
lists["index"].append(level_num)
Now in lists["index"]
you have the list you want as an output and in lists["rewards"]
you get your values.现在在lists["index"]
你有你想要的列表作为 output 并且在lists["rewards"]
你得到你的值。
Alternatively you can open a new list and append to that as well:或者,您也可以打开一个新列表和 append :
levels = []
levels.append(level_num) # In your while loop
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.