csv 从将表示列表的字符串转换回列表中去除剩余的字符串指示符?

smdnsysy  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(81)

我有一个从csv中读取的listdict,用于bootcamp实验室中使用的函数,仅限于基本函数和内置模块和库。我正在做一个类似于抽认卡的东西。
one_dict = [{'Question':'onevalue','Answers':['an_val','two_val','3rd_val'],'Correct Answer':'two_val'}]
我正在阅读它,需要为用户输入的答案添加标签ex:[1]'an_瓦尔' [2] 'two_val'...etc如果用户输入为'1',则会将'an_val'测试为键'Correct Answer'
现在我正在格式化问题答案组合以呈现给用户,我很卡住。这个函数在一个类中,这个类现在没有做任何事情,并且设置了init传递。用户必须输入由逗号分隔的答案,因此必须考虑所有数据类型。

def return_q(self,one_dict):
        #takes a dictionary and looks for "Question" and "Answers" as keys
        #Answers should be list so index counter puts answers list into a dictionary
        #answers = 1:option 2:option 3:option for the purposes of user input
        q_retrive = one_dict[0]['Question']
        index = 0
        answer_dict = {}
        adict = one_dict[0]['Answers']
        1st print(adict)
        adict = adict[1:-1].split(',')
        2nd print(adict)
        for answer in adict:
            index +=1
            answer_dict[index] = answer
        return (q_retrive,answer_dict)

字符串
这成功地返回了一个列表,但在第一个和结尾的答案中有两个引号。第二次打印将使用one_dict [“'an_瓦尔”,'two_val',“3rd_val'"]返回,返回结果为('question', {1: "'an_val", 2: 'two_val', 4: "3rd_val'"})
我已经环顾四周,我已经尝试了明显的adict[1:-1].split(','),我看到了很多职位在这里和其他地方。我还尝试了一个简单的if else循环,看看是否可以让某些东西工作。

adict = adict[1:-1].split(',')
        print(adict)
        for answer in adict:
            if '"' in answer:
                answer.strip('"')
            elif "'" in adict:
                answer.strip("'")
            else:
                pass
            index +=1
            answer_dict[index] = answer
        return (q_retrive,answer_dict)


我还尝试了eval(),尽管它在技术上并不安全

adict1 = one_dict[0]['Answers']
        print(adict1)                       #print the list pulled from the Answers key
        adict = eval(adict1)                #evaluate it
        print(adict)                        #print after evaluation
        print(adict1 == adict)              #is this the same thing?


导致

['1,2,3,4']
['1,2,3,4']
False


这可不只是困惑。
由于我的学业的限制(主要是使用其他库和pandas和ast recs),我没有弄乱所有的选项,但我觉得我错过了一些简单的东西。如果有人能帮我把最后一句话去掉,我会非常感激的。

gzszwxb4

gzszwxb41#

内置的enumerate函数将帮助您实现目标。它接受一个iterable并返回一个包含count(从start开始,默认为0)和迭代iterable获得的值的元组。

from random import choice

questions = [
    {'Question':'onevalue','Answers':['an_val','two_val','3rd_val'],'Correct Answer':'two_val'},
    {'Question':'two_value','Answers':['an_val','two_val','3rd_val'],'Correct Answer':'two_val'},
    {'Question':'3value','Answers':['an_val','two_val','3rd_val'],'Correct Answer':'two_val'},
    ]

def return_q(one_dict):
    #takes a dictionary and looks for "Question" and "Answers" as keys
    #Answers should be list so index counter puts answers list into a dictionary
    #answers = 1:option 2:option 3:option for the purposes of user input
    question, answer = one_dict['Question'], one_dict['Correct Answer']
    answer_dict = dict(enumerate(one_dict['Answers'], start=1))
    # answer_dict = {1:'option', 2:'option', 3:'option'}
    return question, answer_dict, answer

def main():

    question, answer_dict, answer = return_q(choice(questions))
    
    print(f'Question: {question}?')
    for key, val in answer_dict.items(): print(f'{key:.>4}', val)
    user_input = int(input('\n>>>? '))     # need to be int to match answer_dict keys
    if answer_dict[user_input] == answer:  # match value in answer_dict agaist return_q answer
        print('Correct')
    else:
        print('Incorrect')

if __name__ == '__main__': main()

字符串
输出:

Question: onevalue?
...1 an_val
...2 two_val
...3 3rd_val

>>>? 2
Correct

mtb9vblg

mtb9vblg2#

因为一些流浪汉指责我在这个答案https://stackoverflow.com/a/76749747中使用gpt,并篡改了我的帐户,所以我甚至不能回复他们的评论,我必须使用一个新的答案/帐户,而不是在我的第一个答案下回复你的评论。
我改为one_dict['Question']的原因是,它没有什么意义给你的函数一个1字典项目的列表,然后必须引用它作为索引0,one_dict[0]['Question']。只需要通过一个字典。
for key, val in answer_dict.items(): print(f'{key:.>4}', val)只是一个for循环压缩到一行,使用f-strings将键格式化为固定宽度。在问题后给出选项列表。 1.此示例中的answer_dict不是作为列表进行解析,而是作为表示列表的字符串进行解析 这段代码可以工作,参见[https://onlinegdb.com/o2uXewSRI](https://onlinegdb.com/o2uXewSRI)。answer_dict`是一个字典,而不是一个列表或字符串,所以我不确定你是否使用了相同的代码。

相关问题