【问题标题】:How to attribut a different variable to each element of list如何将不同的变量归因于列表的每个元素
【发布时间】:2015-05-08 02:44:42
【问题描述】:

注意我是初学者。

我的问题是:我可以要求 Python 为列表的每个元素分配不同的变量吗?

我创建了一个问题列表和一个答案列表

lst_questions = ['6+11', '3+3', '9+10', '2+7', '11+8', '9+3', '11+9', '3+3', '2+4', '7+4', '4+8', '3+9']
lst_reponses = [17, 6, 19, 9, 19, 12, 20, 6, 6, 11, 12, 12]
var1 = 0
var2 = 0
var3 = 0
var4 = 0
var5 = 0
var6 = 0
var7 = 0
var8 = 0
var9 = 0
var10 = 0
var11 = 0
var12 = 0

a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0
i = 0
j = 0
k = 0
l = 0

我想拥有:

def apply_solution(lst):

    a = lst.index(var1)
    b = lst.index(var2)
    c = lst.index(var3)
    d = lst.index(var4)
    e = lst.index(var5)
    f = lst.index(var6)
    g = lst.index(var7)
    h = lst.index(var8)
    i = lst.index(var9)
    j = lst.index(var10)
    k = lst.index(var11)
    l = lst.index(var12)

    #Solution
    lst[a], lst[b], lst[c], lst[d], lst[e], lst[f], lst[g], lst[h], lst[i], lst[j], lst[k], lst[l] = lst[a], lst[k], lst[j], lst[i], lst[h], lst[g], lst[f], lst[e], lst[d], lst[c], lst[b], lst[l]

    #Verification indice
    #print a,b,c


    return lst


print apply_solution(lst_reponses)

显然,我收到错误:

a = lst.index(var1)
ValueError: 0 is not in list

如何将 lst_reponses 的每个元素归因于 var1 ... var12 我希望我说清楚。

【问题讨论】:

标签: python list variables


【解决方案1】:

如果要关联值,请使用 dict:

lst_questions = ['6+11', '3+3', '9+10', '2+7', '11+8', '9+3', '11+9', '3+3', '2+4', '7+4', '4+8', '3+9']
lst_reponses = [17, 6, 19, 9, 19, 12, 20, 6, 6, 11, 12, 12]
data  = dict(zip(lst_questions,lst_reponses))

{'2+4': 6, '2+7': 9, '3+3': 6, '9+10': 19, '6+11': 17, '3+9': 12, '9+3': 12, '11+9': 20, '11+8': 19, '7+4': 11, '4+8': 12}

向用户提问并验证:

from random import choice
# "3+2" etc.. keys and correct result as value
data = dict(zip(lst_questions, lst_reponses))
# get random key
question = choice(data.keys())

inp = raw_input("What is {}".format(question))

# is user answer match the value 
if int(inp) == data[question]:
    print("Well done")
else:
    print("Incorrect")

【讨论】:

    【解决方案2】:
    lst_reponses = [17, 6, 19, 9, 19, 12, 20, 6, 6, 11, 12, 12]
    from collections import defaultdict
    dct = defaultdict(list)
    for i in xrange(len(lst_reponses)):
        dct["var{}".format(i+1)] = lst_reponses[i]
    
    print dct
    

    【讨论】:

    • 您能解释一下您的代码 sn-p 的作用吗?
    • 为什么在没有重复键的情况下使用默认字典?
    • 创建一个字典,其中键 - var1、var2、var3 等 vals - 元素形成 lst
    猜你喜欢
    • 2018-08-04
    • 2016-11-09
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多