如何遍历列表并创建/保存变量

时间:2014-07-24 01:03:54

标签: python list

如果我有一个清单

subjects = ['Tests', 'Assignments', 'Quizzes']
for i in subjects:
    i = raw_input("What percentage do {} make up your grade \n".format(i))

我知道这段代码不起作用(我试过),但我如何1)遍历列表2)创建变量3)将数据保存到该变量

最后我想要这样我可以用它们来计算更多数据

tests = x%
assignments = x%
quizzes = x%

2 个答案:

答案 0 :(得分:0)

您可以在此处使用列表理解和变量解包技术,例如

subjects = ['Tests', 'Assignments', 'Quizzes']
format_str = "What percentage do {} make up your grade \n"
tests, assignments, quizzes = [raw_input(format_str.format(i)) for i in subjects]

这将获取每个类别的数据并准备一个列表,因为我们知道它只有三个元素,我们可以方便地将值解包为左侧的三个变量。

默认情况下,raw_input将返回String,如果要将用户输入转换为数字,可以像这样转换它们

formatter = "What percentage do {} make up your grade \n".format
tests, assignments, quizzes = [float(raw_input(formatter(i))) for i in subjects]

答案 1 :(得分:0)

thefourtheye建议的答案可以解决你的问题,但它并没有真正扩展。假设您现在有20个主题而不是3个,现在您必须手动创建20个变量:

A, B, C, D, ... = [float(raw_input(formatter(i))) for i in subjects]

使用地图肯定是要走的路。无需为每个主题字符串创建一个变量:

score_map = {'Tests' : 0, 'Assignments' : 0, 'Quizzes' : 0}
for subject in score_map:
    score_map[subject] = float(raw_input("What percentage do {} make up your grade \n".format(subject)))
# Now you can access each score
for subject in score_map:
    print "{0} makes up {1} percent".format(subject, score_map[subject])